如何以编程方式触发 Focusout 事件

问题描述 投票:0回答:2

如何仅使用 JavaScript 而不是 jQuery 以编程方式触发 focusout 事件?

例如,在下面的代码中,想法是它应该警告“Hello,world!”因为调用了 focusout() 函数(或类似的事件引发函数)(focusout() 不是 JS 函数,但就是这个想法)。

function helloWorld () {
  alert('Hello, world!');
}

document.getElementsByTagName( 'form' )[0].addEventListener( 'focusout', function( eventObj ) {
  helloWorld();
});

var event = new Event('focusout');
document.getElementsByTagName( 'form' )[0].dispatchEvent(event);       
<form action="" method="post" id="sampleForm">
	<input type="text" id="linkURL" name="linkURL" placeholder="Link URL"><br>
  <input type="submit" name="action" value="Submit">
</form>

javascript blur focusout
2个回答
7
投票

您可以使用

Event
构造函数来完成。

function helloWorld () {
  alert('Hello, world!');           
}

var event = new Event('focusout');
document.getElementsByTagName( 'form' )[0].dispatchEvent(event);  

document.getElementsByTagName( 'form' )[0].addEventListener( 'focusout', function( eventObj ) {
  helloWorld();
});
<form action="" method="post" id="sampleForm">
	<input type="text" id="linkURL" name="linkURL" placeholder="Link URL"><br>
  <input type="submit" name="action" value="Submit">
</form>


0
投票

我们也可以使用“hideFocus”属性来实现。

例如:

document.getElementById('linkURL').hideFocus;

© www.soinside.com 2019 - 2024. All rights reserved.