需要通过元素onclick函数停止执行Javascript onlick函数

时间:2016-10-25 10:34:09

标签: javascript

<input type = "button" onclick="test()">

Js示例代码:

$('input[type=button]').on('click',(function(e){
       e.preventDefault();
      if(!window.confirm(message)) {
         return false;
       }
   })); 

单击按钮时,我需要停止执行test()以用于其他目的。但目前的情况是它还调用test()而不是返回false。谁能提出建议?

2 个答案:

答案 0 :(得分:1)

如果用户确认,您可以从HTML标记中删除onclick事件并手动将其添加到代码中。它要求您知道哪个函数与onclick标记属性相关联,如果它根据具体情况而变化,则可能会很复杂。这对你有用吗?

// we remove the onclick attribute from the HTML
$('input[type=button]').removeAttribute('onclick');

$('input[type=button]').on('click',(function(e){
   if(!window.confirm(message)) {
       // if user does not confirm, do nothing
       return false;
   } else {
       // if user does confirm, then proceed with the test() function
       test();
   }
})); 

答案 1 :(得分:0)

尝试首先取消绑定之前有效的onclick:

$('input[type=button]').unbind( 'click' );
$('input[type=button]').on('click',(function(e){
       e.preventDefault();
      if(!window.confirm(message)) {
         return false;
       }
   }));