我想知道焦点事件是由程序触发还是人为触发?
我正在写剧本的一部分
jQuery( document ).on( 'focus', '#song_artist_focus', function(event) {
if(event.originalEvent === undefined ){
alert('I am not human');
return;}
alert('I am human') ;
});
Run Code Online (Sandbox Code Playgroud)
当我像这样以编程方式调用这个脚本时
jQuery('#song_artist_focus').focus();
Run Code Online (Sandbox Code Playgroud)
它仍然表明事件是由人触发的。请帮忙 ?
我检查了这个解决方案Check if event is generated by a human。但不适用于焦点事件。
您的问题是该focus事件不会冒泡。
jQuery 通过一点魔法修复了这个问题,使其更像其他事件,但它仍然不像自然冒泡的事件那样工作。
要解决该问题,请使用该focusin事件,因为它会冒泡,然后执行.trigger('focusin')
jQuery(document).on('focusin', '#song_artist_focus', function(event) {
if (event.originalEvent === undefined) {
console.log('I am not human');
} else {
console.log('I am human');
}
});
jQuery('#song_artist_focus').trigger('focusin');Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="song_artist_focus">Run Code Online (Sandbox Code Playgroud)