两个事件处理程序和一个函数.如何防止代码执行两次

Double event handler and one function. How to prevent executing code twice?

本文关键字:何防止 代码 两次 执行 事件处理 两个 程序 一个 函数      更新时间:2023-09-26

我有一个回调函数绑定到两个事件(changefocusout)。然而,我需要focusout仅在与我们交互的元素不是checkbox时发生。

这是示例代码:

$(document).on('focusout change', '.selector', function() {
    if ($(this).is(':checkbox')) {
        // Do stuff and prevent the focusout to trigger. HOW???
    }
    doStuff(); // Action that applies to both cases, but needs to be limited at one execution only
});

上面的代码将执行两次:

  • 当复选框被选中/取消选中时
  • 在复选框外单击时(失去焦点(模糊))

我尝试使用.off,但它最终完全扼杀了focousout处理程序,稍后我将需要它来处理其他不是复选框的元素。

防止focusout处理程序触发某些元素的方法是什么?

您想要做的是

$(document).on('focusout change', '.selector', function(event) {

event是一个事件对象,它具有属性,其中一个属性是type。检查type,您现在可以查看您的函数是否因focusoutchange而被调用,并根据需要运行代码

最好的方法是将两个事件(或更多)影响到相同的函数,如下所示:

文本输入,例如

<input id="myfield" type="text" />

现在是Javascript

var myfield = document.getElementById('myfield');
myfield.onfocus = myfield.onchange = function(e)
{
    //your code
}

Yo甚至可以添加其他元素

button.onclick = myfield.onkeyup = function(e)
{
    //when the client press the enter key
    if(e.key && e.key == "Enter")
    {
        //catch the target
    }
    //when the client click the button
    else if(!e.key || e.target == button)
    {
        //catch the target
    }
    //otherwise you can do not care about the target and just execute your function
}

你必须只知道你可以添加许多元素和许多事件

element1.onfocus = element1.onblur = element2.onchange = element3.onchange = function(e){//your code}