jQuery — click function on a class added via 'addClass' does not respond

安稳与你 提交于 2019-12-11 01:03:33

问题


I've added a class via addClass. I have an onclick function for that added class. However jQuery ignores the click function I created for that class.

I've tested it on JSFIDDLE here

 <style type="text/css">
 .openInfo:hover{color:red}
 .closeInfo:hover{color:blue}
 </style>

 <div class="openInfo">OPEN</div>

<script>
$('.openInfo') //executes correctly
    .click(function() {
        $(this).text("CLOSE");
        $(this).addClass('closeInfo');
        $(this).removeClass('openInfo');
});

$('.closeInfo') //ignored
    .click(function() {
        $(this).text("OPEN");
        $(this).addClass('openInfo');
        $(this).removeClass('closeInfo');
});
</script>

As an aside, for some reason none of the code works on jsfiddle if I use 1.5.2?! That has to be a jsfiddle bug right? Cos I'm getting the same results with 1.5.2 on my testing server at least.


回答1:


Since you are added this class dynamically you need live not click:


$('.closeInfo') //ignored
    .live("click", function() {
        $(this).text("OPEN");
        $(this).addClass('openInfo');
        $(this).removeClass('closeInfo');
});



来源:https://stackoverflow.com/questions/5764908/jquery-click-function-on-a-class-added-via-addclass-does-not-respond

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!