是的,如果您再次调用,您将复制事件处理程序observeRemoveRoom
,但这可能不会引起注意,因为您只是调用在removeClass
找不到类时不执行任何操作的方法,这将是第一个侦听器被触发后的情况。
相反,您可以每次取消绑定并重新绑定点击事件,例如:
var observeRemoveRoom = function(){
var remove_class = function(){
$(this).parent().removeClass('active');
};
$('.remove_room').off('click', remove_class).on('click', remove_class);
}
但是就是说,建议您在此函数之外执行此操作,而不是每次都绑定和取消绑定事件,例如:
$(document).ready(function(){
var remove_class = function(){
$(this).parent().removeClass('active');
};
// If the element exists at dom ready, you can bind the event directly
$('.remove_room').on("click", remove_class);
// If the element is added in dynamically, you can [delegate][1] the event
$('body').on("click", '.remove_room', remove_class);
// Note: Although I've delegated the event to the body tag in this case
// I recommend that you use the closest available parent instead
});
http://api.jquery.com/on/#direct-and-delegated-events:[1 ]