Ryan Gillies
Ryan Gillies

Reputation: 463

Jquery hasClass + If Statement

I want the following loadContent function to load the target div only if the link clicked has a certain class. This is what I've come up with so far:

function loadContent(targetDIV, sourceURL) {
if ( $(this).hasClass("done") ) {
$(""+targetDIV+"").load(""+sourceURL+"");
}
}

<a href="javascript:loadContent('#nav', 'news.php');" class="done">News</a>

The function works without the if statement, but I just can't seem to get the hasClass to work with the if - any thoughts? Thanks!

Upvotes: 4

Views: 14663

Answers (3)

mutex
mutex

Reputation: 7728

Instead of using href="javascript:..." could you perhaps use the jquery click() method to bind your click?

I'm not sure if "this" is set correctly as you've got it but I think using jquery click will ensure "this" is what you're expecting. I also think it's more clear.

Upvotes: 0

Jage
Jage

Reputation: 8086

The reason it does not work because the reference to "this" in your function is not actually referring to the link. Pass the link itself to the function for better results:

function loadContent(linkObj, targetDIV, sourceURL) {
    if ( $(linkObj).hasClass("done") ) {
        $(""+targetDIV+"").load(""+sourceURL+"");
    }
}

<a href="javascript:loadContent(this, '#nav', 'news.php');" class="done">News</a>

Upvotes: 3

user113716
user113716

Reputation: 322492

Change it to the following, and it should work:

<a href="#" onclick="loadContent.call(this, '#nav', 'news.php');" class="done">News</a>

By using .call(), you're setting the value of this in the loadContent function to the current element.

And because we used onclick, this in the inline handler will give you that reference to pass on.

Upvotes: 1

Related Questions