admin管理员组文章数量:1427823
I am using bootstrap tabs and I wanted to do some functions with javascript if LI
is clicked but with conditional, if it's active do nothing, else do this...
I have e up with this code to check if it has a class="active" since bootstrap tabs adds class="active" to LI for the active tab
but it doesn't work well, it always returns true, what I am doing wrong here?
code
var i = $( "li" ).hasClass( "active" );
$( "li" ).click(function() {
if (i == true ) {
console.log("the tab is already active");
}
else {
console.log("selected");
}
});
here is jsfiddle demo
I am using bootstrap tabs and I wanted to do some functions with javascript if LI
is clicked but with conditional, if it's active do nothing, else do this...
I have e up with this code to check if it has a class="active" since bootstrap tabs adds class="active" to LI for the active tab
but it doesn't work well, it always returns true, what I am doing wrong here?
code
var i = $( "li" ).hasClass( "active" );
$( "li" ).click(function() {
if (i == true ) {
console.log("the tab is already active");
}
else {
console.log("selected");
}
});
here is jsfiddle demo
Share Improve this question asked Dec 22, 2014 at 8:39 skyline33skyline33 5735 silver badges18 bronze badges5 Answers
Reset to default 3Use $(this)
for taken current object
$( "li" ).click(function() {
if ($(this).hasClass("active")) {
console.log("the tab is already active");
}
else {
console.log("selected");
}
});
Fiddle
Check hasClass for clicked li:
$( "li" ).click(function() {
if ($(this).hasClass('active') ) {
console.log("the tab is already active");
}
else {
console.log("selected");
}
});
Because $("li") returns all the li tags. And the initial state of the first li tab is active, so the i variable is always true.
Change the codes to what @Bhojendra Sah wrote will work.
You can try this as well for dynamic elements:
$(document).on('click', "li.active", function (e) {
console.log("the tab is already active");
}).on('click', "li:not(.active)", function (e) {
console.log("selected");
});
Example
$( "li" ).click(function() {
if ($(this).hasClass("active") ) {
console.log("the tab is already active");
}
else {
console.log("selected");
}
});
本文标签: javascriptjquery if has class issueStack Overflow
版权声明:本文标题:javascript - jquery if has class issue - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745507758a2661323.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论