make div clickable with jquery
jsfiddle: http://jsfiddle.net/FgZnK/1/
开发者_如何学PythonClicking on the box goes to a page not found. How can I make this work?
HTML
<div class="myBox"></div>
jQuery
$(".myBox").click(function(){
window.location=$(this).attr("http://google.com");
return false;
});
This is the correct code:
$(".myBox").click(function() {
window.location = "http://google.com";
});
http://jsfiddle.net/FgZnK/2/
HTML
<div class="myBox" data-href="http://google.com/">
</div>
JS
$(".myBox").click(function(){
window.location = $(this).attr("data-href");
return false;
});
In this chunk here:
$(".myBox").click(function(){
window.location=$(this).attr("http://google.com");
return false;
});
You're actually trying to read the non-existent attribute named http://google.com
.
Instead, just use:
$(".myBox").click(function(){
window.location = 'http://google.com';
});
If instead you want the actual destination to be in the mark up rather than the script, use:
$(".myBox").click(function(){
window.location = $(this).attr('href');
});
and put an href
attribute on your DIV, just like you would on an A link.
There's no need for return false
in any of these handlers because a DIV doesn't have a default action that needs preventing, unlike a normal link.
Open in new window....
$("#whatever").click(function() {
window.open(
'https://www.example.com',
'_blank' // open in new window
);
});
window.location="http://google.com";
This is the faulty line :
window.location=$(this).attr("http://google.com");
This doesn't make any sense, you're trying to change the location to the value of the attribute named "http://google.com" of your div.
Just correct it like this :
$(".myBox").click(function(){
window.location= "http://google.com";
return false;
});
$(".myBox").click(function(){
window.location.href="http://google.com";
return false;
});
精彩评论