开发者

jQuery returns "undefined" trying to find href

开发者 https://www.devze.com 2023-02-19 18:57 出处:网络
I\'m trying to wrap this into a function: //Entire Div Clickable function clickableDiv(){ win开发者_如何学Pythondow.location = $(this).find(\"a\").attr(\"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);
0

精彩评论

暂无评论...
验证码 换一张
取 消