javascript - 在元素上触发 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/
当您单击该按钮时,您只会看到一个警报。文本字段的颜色不会改变。
解决方案
而不是使用 $("#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>
推荐阅读
- c# - 在 Unity3D 的 System.Drawing 中找不到位图
- python - 有没有什么方法可以用关键字、日期来提取
- typescript - TypeScript:按类型属性选择数组的元素
- android - 处理从新的 Google 相册应用中选择的文件的正确方法
- android - xml 中的 new Date() 不能与数据绑定一起工作
- python - 使用 psql 10.9 和使用 python3.7 的 sqlalchemy 从隔离事务返回行
- python - 如何根据条件更新火花数据框中的行
- spring - TransactionalEventListener 不会启动
- axapta - 如何在代码中构建或调整数据源?
- javascript - 故事书 + MDX