2017-02-16 25 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是的,很好,謝謝。 –

相關問題