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 badges
Add a ment  | 

5 Answers 5

Reset to default 3

Use $(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