jQuery:在 blur() 事件之前触发 click()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10652852/
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-08-26 09:38:45  来源:igfitidea点击:

jQuery: fire click() before blur() event

jqueryclickonblur

提问by Egor Sazanovich

I have an input field, where I try to make autocomplete suggestion. Code looks like

我有一个输入字段,我尝试在其中提出自动完成建议。代码看起来像

<input type="text" id="myinput">
<div id="myresults"></div>

On input's blur()event I want to hide results' div:

在输入的blur()事件中,我想隐藏结果的 div:

$("#myinput").live('blur',function(){
     $("#myresults").hide();
});

When I write something into my input I send request to server and get json response, parse it into ul->li structure and put this ul to my #myresultsdiv.

当我在输入中写入内容时,我将请求发送到服务器并获得 json 响应,将其解析为 ul->li 结构并将此 ul 放入我的#myresultsdiv。

When I click to this parsed li element I want to set value from li to input and hide #myresultsdiv

当我点击这个解析的 li 元素时,我想将 li 的值设置为输入并隐藏#myresultsdiv

$("#myresults ul li").live('click',function(){
     $("#myinput").val($(this).html());
     $("#myresults").hide();
});

Everything is going good, but when I click to my li blur()event fires before click()and input's value don't get li's html.

一切都很顺利,但是当我点击我的 liblur()事件之前触发click()并且输入的值没有得到 li 的 html。

How can I set up click()event before blur()?

click()之前如何设置事件blur()

回答by Alexey Lebedev

Solution 1

解决方案1

Listen to mousedowninstead of click.

mousedown而不是click

The mousedownand blurevents occur one after another when you press the mouse button, but clickonly occurs when you release it.

mousedownblur当您按下鼠标按钮事件接二连三发生,但click只有当你释放它发生。

Solution 2

解决方案2

You can preventDefault()in mousedownto block the dropdown from stealing focus. The slight advantage is that the value will be selected when the mouse button is released, which is how native select components work. JSFiddle

您可以preventDefault()mousedown以阻止偷焦点下拉。稍微的好处是当释放鼠标按钮时会选择该值,这就是原生选择组件的工作方式。JSFiddle

$('input').on('focus', function() {
    $('ul').show();
}).on('blur', function() {
    $('ul').hide();
});

$('ul').on('mousedown', function(event) {
    event.preventDefault();
}).on('click', 'li', function() {
    $('input').val(this.textContent).blur();
});

回答by adeneo

$(document).on('blur', "#myinput", hideResult);

$(document).on('mousedown', "#myresults ul li", function(){
     $(document).off('blur', "#myinput", hideResult); //unbind the handler before updating value
     $("#myinput").val($(this).html()).blur(); //make sure it does not have focus anymore
     hideResult(); 
     $(document).on('blur', "#myinput", hideResult);  //rebind the handler if needed
});

function hideResult() {
     $("#myresults").hide();
}

FIDDLE

小提琴

回答by geckob

I faced this issue and using mousedownis not an option for me.

我遇到了这个问题,使用mousedown不是我的选择。

I solved this by using setTimeoutin the handler function

我通过setTimeout在处理程序函数中使用解决了这个问题

        elem1.on('blur',function(e) {

            var obj = $(this);

            // Delay to allow click to execute
            setTimeout(function () {
                if (e.type == 'blur') {

                  // Do stuff here

                }
            }, 250);
        });

        elem2.click( function() {
            console.log('Clicked');
        });

回答by dule

I just answered a similar question: https://stackoverflow.com/a/46676463/227578

我刚刚回答了一个类似的问题:https: //stackoverflow.com/a/46676463/227578

An alternative to the mousedown solutions is have it ignore blur events caused by clicking specific elements (i.e., in your blur handler, skip the execution if it's a result of clicking a specific element).

mousedown 解决方案的替代方案是忽略由单击特定元素引起的模糊事件(即,在您的模糊处理程序中,如果是单击特定元素的结果,则跳过执行)。

$("#myinput").live('blur',function(e){
     if (!e.relatedTarget || !$(e.relatedTarget).is("#myresults ul li")) {
         $("#myresults").hide();
     }
});

回答by Andriy

Mousedown solutions does not work for me, when I click on non button elements. So here is what I've done with blur function in my code:

当我单击非按钮元素时,Mousedown 解决方案对我不起作用。所以这是我在代码中使用模糊函数所做的:

.on("blur",":text,:checkbox,:radio,select",function() {
/*
* el.container 
* container, you want detect click function on.
*/
            var outerDir = el.container.find(':hover').last();
            if (outerDir.length) {
                if ($.inArray(outerDir.prop('tagName'), ["A","SELECT"] ) != -1 || outerDir.prop('type') == 'button' || outerDir.prop('type') == 'submit') {
                    outerDir.click();
                }
                if (outerDir.prop('type') == 'checkbox') {
                    outerDir.change();
                }
                return false;
            }
/*          
* YOUR_BLUR_FUNCTION_HERE;
*/
});