jQuery:将类添加到新元素后,不能通过单击该类来触发事件 [英] jQuery: after adding class to a new element, can't trigger event by clicking on that class

查看:71
本文介绍了jQuery:将类添加到新元素后,不能通过单击该类来触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在尝试的:当我点击具有类.main的元素时,该类被重新分配给下一个元素。单击下一个元素(新的.main元素)时,.main将重新分配给下一个元素,依此类推。这是我的代码:

Here's what I'm attempting: when I click on an element with the class .main, that class is reassigned to the next element. When the next element (the new .main element) is clicked on, .main is reassigned to the next element, and so on. Here's my code:

$('.main').click(function() {
  $(this).removeClass("main").addClass("other");
  $(this).next().removeClass("other").addClass("main");
});

当我点击原始.main元素时,将转移该类。但是,单击新的.main元素不会再次触发该事件。是什么导致这个?我完全是错误的做法吗?

When I click on the original .main element, the class is transferred. However, clicking on the new .main element does not trigger the event again. What causes this? Am I going about this entirely the wrong way?

这是一个小提琴:

http://jsfiddle.net/UHLft/2/

推荐答案

事件绑定到DOM节点,而不是类名(尽管类名当然用于初始选择相关元素);因此,当类名更改时,事件不再被绑定,因此您需要使用 on()

Events are bound to the DOM nodes, not the class-names (though the class-names are, of course, used to initially select the relevant element(s)); so when the class-name changes the events are no longer bound, so you need to delegate the event-handler to the parent with on():

$('#container').on('click', '.main', function () {
    $(this).removeClass("main").addClass("other");
    $(this).next()
        .removeClass("other").addClass("main");
});

JS小提琴演示

参考文献:

这篇关于jQuery:将类添加到新元素后,不能通过单击该类来触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆