2017-02-16 26 views
3

我创建了一个click事件,它改变了一个按钮的标识符。我在同一个按钮上创建了第二个点击事件,但是这次使用了新ID。当我再次单击按钮时。我总是有与旧的ID第一个行为。这里是更好地说明这个例子的代码。我们的想法是做两种不同的行为与同一按钮如何用同一个按钮实现两种不同的行为

$('#button').on('click',function() { 
    $(this).attr('id','buttonBis'); 
}); 

$('#buttonBis').on('click',function() { 
    alert('here'); 
}); 
+0

2 ID? – guradio

+0

就像@Rory麦克罗森说过的。我应该改变类而不是ID。 – KubiRoazhon

回答

6

如果您要改变标识符动态,那么你就需要使用委派事件处理程序:

$(document).on('click', '#button', function() { 
 
    $(this).attr('id', 'buttonBis'); 
 
}); 
 

 
$(document).on('click', '#buttonBis', function() { 
 
    alert('here'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<button id="button">Click me twice to see the alert()</button>

请注意,动态更改id属性不被认为是一个好主意,应尽可能避免。我建议添加/删除类将是一个更好的选择。

+0

比另一个好得多。 +1 –

+0

是的,你是对的。导致id使项目独一无二。我会通过添加一些类来改变它。谢谢 – KubiRoazhon

0

1个按钮创建函数到事件分配给新的按钮编号,并移除附接(防止重复)事件通过其科恩替换DOM节点,

$('#button').on('click',function() { 
 
    $(this).attr('id','buttonBis'); 
 
    //clone the node then reissign to the same node 
 
    // which removes the previous attached events 
 
    var self = this.cloneNode(true); 
 
    $(this).replaceWith(self); 
 
    newevent(); 
 
}); 
 

 

 
var newevent = function() { 
 
\t $('#buttonBis').on('click',function() { 
 
     alert('here'); 
 
    }); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="button" >Click Me twice </button>

+1

Just FYI而不是'this.parentNode.replaceChild ...''jQuery有'replaceWith()'方法,你可以使用 –

+0

@RoryMcCrossan是的,很好,谢谢。 –

相关问题