简体   繁体   English

jQuery基本切换仅一种方式

[英]jQuery basic toggling only working one way

I've created some quick jQuery toggle code: 我创建了一些快速的jQuery切换代码:

$("#expander.closed").click(function(){
    console.log("opening");
    $("#expander").removeClass();
    $("#expander").addClass("open");
});
$("#expander.open").click(function(){
    console.log("closing");
    $("#expander").removeClass();
    $("#expander").addClass("closed");
});

The idea is that everytime you click #expander the class toggles between open and closed . 这个想法是,每次你点击#expander之间的阶级切换openclosed

However, for some reason, it only works once, changing from closed to open , and then goes no further. 但是,由于某种原因,它只能工作一次,从closed变为open ,然后再没有其他作用了。

I have no clue why. 我不知道为什么。 Here's a jsFiddle . 这是一个jsFiddle

I think in the beginning, when you bind the events, .closed class does not exists, so the event does not get bound 我认为一开始,当您绑定事件时, .closed类不存在,因此该事件不会被绑定

May be you should bind the event to some other criteria, or use live . 可能您应该将该事件绑定到其他条件,或者使用live which is deprecated though 虽然不推荐使用

Better way would be like this 更好的方法是这样的

$("#expander_parent").on('click', '#expander.closed', function(){
    // Do your stuff
})

Just bind it using the id and toggle the classes using .toggleClass 只需使用id绑定它,然后使用.toggleClass切换类

$("#expander").click(function(){
    $(this).toggleClass('open closed');
});

FIDDLE 小提琴

if you need to do other functions depending on which class it has you can check like this 如果您需要根据具有的类执行其他功能,可以像这样检查

$("#expander").click(function(){
    var $this = $(this);
    $this.toggleClass('open closed');
    if($this.hasClass('open')){
       // do your open code
    }else{
       // do your close code
    }   
});

FIDDLE 小提琴

You can do this and add your other related operations within the if/else conditions 您可以执行此操作,并在if / else条件下添加其他相关操作

HTML: HTML:

<div id="expander" class="closed">Click Me</div>

CSS: CSS:

.closed {
    background-color: red;
}

.open {
    background-color: blue;
}

Javascript: Javascript:

$("#expander.closed").click(function (){
    if ($('#expander').attr('class') === 'closed') {
          $('#expander').attr('class', 'open');

          // Add other related functions here
    } else {
        $('#expander').attr('class', 'closed');

        // Add other related functions here
    }    
});

http://jsfiddle.net/mCDwy/1/ http://jsfiddle.net/mCDwy/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM