[英]Find .class in parent <li> by JQuery
<!--HTML-->
<ul class="navigation">
<li>
<a class="handle-link" href=""><img src=""/>Dashboard</a>
</li>
<li class="active">
<a href="#" class="expand"><img src=""/>Multiple</a>
<ul>
<li class="current">
<a class="handle-link sub-menu" href="">One</a>
</li>
<li>
<a class="handle-link sub-menu" href="">Two</a>
</li>
<li>
<a class="handle-link sub-menu" href="">Three</a>
</li>
</ul>
</li>
<li >
<a class="handle-link" href=""><img src=""/>Single</a>
</li>
</ul>
$('a.handle-link').click(function (e) {
e.preventDefault();
var currentMenuItem = $(this);
var parentLI = $(currentMenuItem).closest('li');
if ($(currentMenuItem).hasClass('sub-menu')) {
if ($(parentLI.hasClass('current'))) {
alert('This is current');
}
else {
//Error here-
alert('This is not current'); //This is not executing
}
}
else {
alert('this is somewhere else.');
}
});
When I click on "Two", it also returns "This is current".当我点击“Two”时,它也会返回“This is current”。 But it should return "This is not current".但它应该返回“这不是最新的”。
Any help?有什么帮助吗?
Problem is in your if
statement because you are passing a jQuery object( $(parentLI.hasClass('current'))
) to it which will always be truthy.问题出在您的if
语句中,因为您将一个 jQuery 对象( $(parentLI.hasClass('current'))
)传递给它,该对象将始终为真。
So just remove the wrapping $()
call, so that the value returned by hasClass
is evaluated by the if
statement所以只需删除包装$()
调用,以便由if
语句评估hasClass
返回的值
if (parentLI.hasClass('current')) {
alert('This is current');
} else {
//Error here-
alert('This is not current'); //This is not executing
}
$(parentLI.hasClass('current'))
is always going to be truthy since jQuery object is returned. $(parentLI.hasClass('current'))
总是会是真的,因为 jQuery 对象被返回。 You need get rid of the wrapping $()
你需要摆脱包装$()
if (parentLI.hasClass('current')) { ...
Try this:尝试这个:
$('a.handle-link').click(function (e) {
e.preventDefault();
var currentMenuItem = $(this);
var parentLI = currentMenuItem.parent('li');
if (currentMenuItem.hasClass('sub-menu')) {
if (parentLI.hasClass('current')) {
alert('This is current');
} else {
alert('This is not current');
}
} else {
alert('this is somewhere else.');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.