javascript 如果单击提交按钮,则防止执行 onblur 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15196352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:50:08  来源:igfitidea点击:

Prevent onblur code to execute if clicked on submit button

javascriptjqueryonclickonblur

提问by Palak Tanejaa

By the following code I wish to "DO SOMETHING" on "ONBLUR" of element id="eg1" only if the onblur event was not caused due to "ONCLICK" on the submit button.

通过以下代码,我希望仅当 onblur 事件不是由于提交按钮上的“ONCLICK”引起时,才对元素 id="eg1" 的“ONBLUR”进行“DO SOMETHING”。

    $(document).ready(function() {  
     $('#eg1').blur(function() {
      if(!($("#SubmitBut").click())) {
             //do something
      }
     });
    });

For Eg : if the user changes value of the “eg1” text field and clicks on the next text field then the DO SOMETHING code must run, but in case the user changes value of the the “eg1” field and then clicks on the SUBMIT button, then the DO SOMETHING code must not run.

例如:如果用户更改“eg1”文本字段的值并单击下一个文本字段,则必须运行 DO SOMETHING 代码,但如果用户更改“eg1”字段的值然后单击提交按钮,则不能运行 DO SOMETHING 代码。

Is it the correct way to do so ?? Please guide.

这是正确的方法吗?请指导。

回答by Diode

blurevent of an element triggers before clickevent of another. So one way is to use mousedownand mouseupevents to toggle a flag, because mousedownevent of one element triggers before blurevent of another one.

blur一个元素的click事件在另一个元素的事件之前触发。所以一种方法是使用mousedownmouseup事件来切换标志,因为mousedown一个元素的blur事件在另一个元素的事件之前触发。

$("#eg1").on("blur", function(e){
  if($("#submit").data("mouseDown") != true){
      alert("DO SOMETHING");
  }
});

$("#submit").on("mousedown", function(e){
    $("#submit").data("mouseDown", true);
  });

$("#submit").on("mouseup", function(e){
    $("#submit").data("mouseDown", false);
  });

回答by D3V

Update:

更新:

$('input[type="submit"]').mousedown(test);

$('input[type="submit"]').mousedown(test);

Have a look at this fiddle JSFiddle to address your problem. Use the console to view the events triggered and suppressed after specific actions are performed.

看看这个小提琴JSFiddle 来解决你的问题。使用控制台查看执行特定操作后触发和抑制的事件。

You should suppress the event handler that is bound to the text when clickor submitis performed.

您应该在执行click或时取消绑定到文本的事件处理程序submit

回答by A.T.

A trick -

 $(document).ready(function() {  
var flag = false;
     $('#eg1').blur(function() {
flag = true;
      if(!($("#SubmitBut").click())) {
if(flag) 
   return false;            
 //do something
      }
     });
    });