首页 > 解决方案 > 在元素上触发 JQuery blur() 时,AddEventListener blur 不起作用

问题描述

我有一个输入元素,并且有两个模糊事件。我将第一个添加为 eventListener,第二个添加为该元素的 onBlur。

我添加了一个按钮并在单击按钮时调用一个方法。该方法触发元素上的空模糊事件。

它不会触发我添加为 eventListener 的 onBlur。

<form id="form">
  <input type="text" placeholder="text input">
  <input type="password" placeholder="password" id="password" onBlur="Hello();">
  <input type= "button" value ="Click" onClick=TriggerBlur();>
</form>


<script>
const password = document.querySelector('input[type="password"]');
password.addEventListener('blur', (event) => {
  event.target.style.background = 'pink';
});

function TriggerBlur(){
    $("#password").blur();
}

function Hello(){
    alert("Hello");
}
</script>

这是 jsFiddle:https ://jsfiddle.net/17gsozLd/

当您单击该按钮时,您只会看到一个警报。文本字段的颜色不会改变。

标签: javascriptjquery

解决方案


而不是使用 $("#password").blur();

使用,dispatchEvent:

const event = new Event('blur');
password.dispatchEvent(event);

所以,你的最终代码应该是这样的:(不需要jquery)

const password = document.querySelector('input[type="password"]');
password.addEventListener('blur', (event) => {
  event.target.style.background = 'pink';
});

function TriggerBlur(){
  const event = new Event('blur');
  password.dispatchEvent(event);
}

function Hello(){
    alert("Hello");
}
<form id="form">
  <input type="text" placeholder="text input">
  <input type="password" placeholder="password" id="password" onBlur="Hello();">
  <input type= "button" value ="Click" onClick=TriggerBlur();>
</form>


推荐阅读