在同一个按钮上停止其中一个点击事件

时间:2016-03-20 13:18:43

标签: javascript jquery events preventdefault

我按钮,上面有两个点击事件。 我要做的是防止该按钮上的两个或所有事件依赖于标准。

我尝试使用event.preventDefault();event.stopPropagation();以及return false;,但没有任何方法可以正常使用。

/* I need to stop $('button') event if the if condition
inside $('#btn') event passed */

$('#btn').click(function(e){
  var term = $('#term').val();

  if(term != '') {
    //e.preventDefault();
    //e.stopPropagation();
    return false;
    alert(2);
  } else {
    // continue
  }
});

$('button').click(function(e){
  alert(1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="term" type="text" placeholder="type here ..">
<button type="button" id="btn">Check</button>

JSfiddle example

2 个答案:

答案 0 :(得分:1)

要突破您的功能,请仅使用return;(而不是return false;

此外,您无法在return之后设置任何代码,所以请执行以下操作:

$('#btn').click(function(e){
  e.preventDefault();

  var term = $.trim( $('#term').val() );

  if(term !== "") {
    alert("Value exists! I'm breaking any further operations.");
    return; // "Exit" my function
    // YOU CANNOT WRITE CODE AFTER A RETURN STATEMENT!
  } else { // Else is actually not needed but it's cool to have it for clearance
    alert("Value is empty.");
  }
});

$('button').click(function(e){
  alert(1); // You'll see this in any case.
});

扩展您的问题如何阻止警报(1)弹出

&#13;
&#13;
$('#btn').click(function(e){
  e.preventDefault();

  this.term = $.trim( $('#term').val() );

  if(this.term) {
    alert("Value exists!");
  } else {
    alert("Value is empty.");
  }
});

$('button').click(function(e){
  if(!this.term) {
    alert(1); 
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="term" type="text" placeholder="type here ..">
<button type="button" id="btn">Check</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我假设您要停止这两个事件。如果是这样,你应该在你的$(&#39;按钮&#39;)中添加子句。单击()处理程序。 首先,在$(&#39;#btn&#39;)。click()处理程序添加属性以检查事件是否应该停止:

if(term != '') {
    //e.preventDefault();
    //e.stopPropagation();
    this.stop = 1;
...

然后检查一下:

  if (this.getAttribute("id") !== "btn" || this.stop !==1) {
      alert(1);
  }

此处JSFiddle

相关问题