jQuery — click function on a class added via '

2019-07-09 13:44发布

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条回答
聊天终结者
2楼-- · 2019-07-09 14:25

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');
});

查看更多
登录 后发表回答