2012-04-09 77 views
1

如何動態更改onclick方法的按鈕?動態更改onclick方法

我有兩種方法,一種方法的成功,我想..just設置其他方法,對一個按鈕

+0

請包括HTML和jQuery。 – iambriansreed 2012-04-09 13:21:58

回答

3

的成功轉移由於您使用jQuery,你會用$.on$.off綁定和取消綁定事件。

如果您已經連接了您的處理程序是這樣的:

$("#foo").on("click", function(e) { 
    // event handler 
}); 

你可以刪除該處理程序並添加另一個像這樣:

$("#foo") 
    .off("click") 
    .on("click", function(e){ 
    // new event handler 
    }); 

需要注意的是$.on$.off是首選的方法是很重要的現在使用jQuery 1.7。有關這些方法的更多信息,請參閱the documentation以及宣佈它們的the blog post

0

從jQuery 1.7開始,.on()方法是將事件處理程序附加到文檔的首選方法。

0

給您的按鈕的id,和第一種方法中,添加一行:

getElementById("THE_ID_OF_THE_BUTTON").onclick = theOtherMethod; 
0
<input id="btn" type="button" onclick="success();" value="click me!" /> 
<script> 
    var btn = document.getElementById('btn'); 
    function success(){ 
     alert('something'); 
     btn.onclick = otherFunction; 
    } 

    function otherFunction(){ 
     alert('Something new'); 
     // Now when you clik btn this code is going to be executed 
     btn.onclick = success; 
    } 

</script>