Jquery hasClass + If Statement [英] Jquery hasClass + If Statement
问题描述
我希望以下loadContent函数仅在单击的链接具有某个类时才加载目标div。这就是我到目前为止所提出的:
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>
该函数在没有if语句的情况下工作,但我似乎无法让hasClass工作与if - 任何想法?谢谢!
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!
推荐答案
将其更改为以下内容,它应该有效:
Change it to the following, and it should work:
<a href="#" onclick="loadContent.call(this, '#nav', 'news.php');" class="done">News</a>
使用 .call ()
,你在 loadContent
函数中将这个
的值设置为当前元素。
By using .call()
, you're setting the value of this
in the loadContent
function to the current element.
因为我们使用 onclick
,这个
内联处理程序将为您提供传递的引用。
And because we used onclick
, this
in the inline handler will give you that reference to pass on.
这篇关于Jquery hasClass + If Statement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!