2012-04-09 73 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>