当打字光标离开输入文本字段时如何触发函数?

Ama*_*man 2 javascript

我想在打字光标离开输入文本字段时触发一个函数。这样的事件存在吗?如果有人知道请告诉我,谢谢。

// to trigger this function
function trigger () {
    console.log("no longer able to type in input text);
}
Run Code Online (Sandbox Code Playgroud)

bas*_*sic 6

只需使用 onblur 即可。您可以在 vanilla js 和 jquery 中执行此操作。

香草Js:

function test() {
  alert('Exited');
}

document.getElementById('waffle').addEventListener('blur', function(){
  alert('exited waffle');
});
Run Code Online (Sandbox Code Playgroud)
<input type="text" onblur="test()">
<input type="text" id="waffle">
Run Code Online (Sandbox Code Playgroud)

使用 JQuery:

$('#test').on('blur', function(){
  alert('exited');
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="test" type="text">
Run Code Online (Sandbox Code Playgroud)

Jquery 参考: https: //api.jquery.com/blur/

原版: https: //developer.mozilla.org/en-US/docs/Web/Events/blur