开发者

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

开发者 https://www.devze.com 2023-02-28 12:25 出处:网络
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 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('openInf开发者_运维知识库o');
});

$('.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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号