如何强制在 JavaScript 中发生模糊事件?

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

How do I force a blur event to occur in JavaScript?

javascriptjquery

提问by Jason Thompson

Here's what I want to do. I want to trigger an event every time a select element changes. I have a multiline select and when I make changes (click on elements), it does not change until the select box loses focus. So I'm trying to force a blur every time the select box is clicked. That way if it changes, it will trigger the changed event. If it doesn't change, nothing will happen.

这就是我想要做的。我想在每次选择元素更改时触发一个事件。我有一个多行选择,当我进行更改(单击元素)时,它不会更改,直到选择框失去焦点。因此,每次单击选择框时,我都试图强制进行模糊处理。这样,如果它发生变化,它将触发 changed 事件。如果它不改变,就什么都不会发生。

How do I do this? Am I even approaching this the right way? Jquery answers are okay as well.

我该怎么做呢?我什至以正确的方式接近这个吗?Jquery 的答案也不错。

采纳答案by Jason Thompson

Okay, Here's what was going on. I was including the -vsdoc version of JQuery instead of the actual JQuery library. This also fixes some issues I was having with some plugins such as blockUI.

好的,这是怎么回事。我包含了 JQuery 的 -vsdoc 版本,而不是实际的 JQuery 库。这也解决了我在使用某些插件(例如 blockUI)时遇到的一些问题。

回答by Muffun

In addition to Ender the full code could be something like this.

除了 Ender 之外,完整的代码可能是这样的。

$('#mySelectBox').change(function() {
    $('#thingToBlur').blur();
})

Reference: http://api.jquery.com/blur/

参考:http: //api.jquery.com/blur/

回答by Ender

Using jQuery do:

使用 jQuery 做:

$('#mySelectBox').change(function() {
   //do things here
});

According to the documentation at http://api.jquery.com/change/, the event is triggered immediately when the user makes a selection.

根据http://api.jquery.com/change/上的文档,当用户进行选择时会立即触发该事件。

Check out this demo to verify that this works: http://jsfiddle.net/AHM8j/

查看此演示以验证它是否有效:http: //jsfiddle.net/AHM8j/

回答by Marc B

You could attach an onclick handler to the select and the individual options. basically onclick="this.blur();". I've always found that click events on <select>elements to be a pain, as nothing happens at the point you expect it to.

您可以将 onclick 处理程序附加到选择和单个选项。基本上onclick="this.blur();"。我一直发现<select>元素上的点击事件很痛苦,因为在您期望的时候什么也没有发生。

回答by tanner burton

This will find the element with the focus and trigger the blur event.

这将找到具有焦点的元素并触发模糊事件。

function blur(){
    document.querySelectorAll('input,textarea').forEach(function(element){
        if(element === document.activeElement) {
            return element.blur();
        }
    });
}