jQuery returns "undefined" trying to find href
I'm trying to wrap this into a function:
//Entire Div Clickable
function clickableDiv(){
win开发者_如何学Pythondow.location = $(this).find("a").attr("href");
return false;
}
and then call it by:
$("div.promo1").click(function(){
clickableDiv();
});
But it returns a url of: www.mywebsite.com/undefined
Any ideas what I'm doing wrong?
Thanks.
The trouble is that you're calling clickableDiv
normally, rather than binding it to an event. You are running it from an event handler, rather than setting it as the event handler. This means that this
is not set to the element.
You should set the function as the event handler instead.
$("div.promo1").click(clickableDiv);
function clickableDiv(div) {
window.location = $(div).find("a").attr("href");
}
$("div.promo1").click(function() {
clickableDiv(this);
});
You have to pass the reference to the DIV into the clickableDiv
function.
Update: Alternative solution:
function clickableDiv() {
window.location = $(this).find("a").attr("href");
}
$("div.promo1").click(clickableDiv);
精彩评论