简体   繁体   English

如何停止触发onfocus事件?

[英]How to stop onfocus event from firing?

I want to catch chatbox input field onfocus event to know that user has read the messages. 我想捕获chatbox输入字段onfocus事件,以了解用户已阅读消息。 When onfocus event is trigered I will send ajax to server that messages has been seen. 当触发onfocus事件时,我会将ajax发送到已看到消息的服务器。

Whatever appproach I try I always get onfocus event constantly firing. 无论我尝试哪种方法,我总是会不断触发onfocus事件。

<input type="text" name="content<?php echo $id; ?>" placeholder="Type message..." onfocus="chatboxInputInFocus(<?php echo $id; ?>)"/>

and JS: 和JS:

function chatboxInputInFocus(swap_id){
    alert(swap_id);
    return;
}

What I get is constant alert. 我得到的是持续不断的警觉。 How to catch only the moment when input comes to focus? 如何仅捕捉输入集中的时刻? JS or Jquery. JS或Jquery。

Don't use alert() for debugging, as it triggers your focus. 不要使用alert()进行调试,因为它会触发您的焦点。
Use console.log() instead, and your code will work. 使用console.log()代替,您的代码将起作用。

 function chatboxInputInFocus(swap_id){ console.log(swap_id); return; } 
 <input type="text" name="content123" placeholder="Type message..." onfocus="chatboxInputInFocus(123)"/> 

You can use the handy .one method of jQuery . 您可以使用jQuery的便捷.one方法。

$(document).ready(function(){
    $("input").one('focus', function(){
        alert('Just once!');
    });
});

https://api.jquery.com/one/ https://api.jquery.com/one/

Need here to pass the event object in the onfocus function param and do the preventdefault. 这里需要在onfocus函数参数中传递事件对象并执行preventdefault。 function chatboxInputInFocus(swap_id){ alert(swap_id); ev.preventDefault(); return; } function chatboxInputInFocus(swap_id){ alert(swap_id); ev.preventDefault(); return; } onfocus="chatboxInputInFocus(event,id)" ` function chatboxInputInFocus(swap_id){ alert(swap_id); ev.preventDefault(); return; } onfocus =“ chatboxInputInFocus(event,id)”`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM