![](/img/trans.png)
[英]How to simulate TAB on ENTER keypress in javascript or jQuery
[英]How to trap “blur” or “keypress” enter 13 in javascript jquery - OR not, both
我想在表單字段上捕獲“輸入”和“模糊”。 如果我點擊“ enter”和“ tab”,它也會觸發模糊事件……只有一個觸發器,所以“ OR”不是“ AND”。
$('#login-input-password').bind('blur keypress', function(e){
if (e.type == 'blur' || e.keyCode == 13) {
// do something only once, not twice
// e.g., if I hit "[enter"] and tab to blur, I don't want it to call twice...
}
});
功能用法
function bindTriggerEnterOrBlur(selector,myFunction)
{
$(selector).bind('blur keypress', function(e){
if (e.type == 'blur' || e.keyCode == 13) {
if (!$(selector).data('has-triggered')) {
$(selector).data('has-triggered', true);
// do something only once, not twice
myFunction();
// e.g., if I hit "[enter"] and tab to blur, I don't want it to call twice...
}
}
});
$(selector).bind('focus', function(e){
$(selector).data('has-triggered', false);
$(selector).select();
});
}
調用功能
bindTriggerEnterOrBlur('#login-input-email',submitLoginEmail);
其中commitLoginEmail是為觸發器執行某些操作的函數,例如,
function submitLoginEmail()
{
// submit on enter...
var email = $("#login-input-email").val();
if(validEmail(email))
{
submitNextLogin();
}
}
如果我的要求正確,那么您只想執行一次回調,但是目前執行兩次。
如果是這種情況,那么您將需要某種方式來指示是否已經調用了回調。
一種方法是使用數據屬性
$('#login-input-password').bind('blur keypress', function(e){
if (e.type == 'blur' || e.keyCode == 13) {
if (!$(this).data('done') {
$(this).data('done', true);
// do something only once, not twice
// e.g., if I hit "[enter"] and tab to blur, I don't want it to call twice...
}
}
});
您還需要另一個事件處理程序來重置元素的done屬性
$('#login-input-password').bind('focus', function(e) {
$(this).data('done', false);
});
您正在執行OR。 您需要異或(異或),這必須使用比較組合來完成。
if (( (e.type == 'blur') && !(e.keyCode == 13)) ||
(!(e.type == 'blur') && (e.keyCode == 13))) {
// do something only once, not twice
// e.g., if I hit "[enter"] and tab to blur, I don't want it to call twice...
}
但是,您想防止腳本再次觸發,因此您需要進行更多狀態比較,以確保異步事件處理程序知道發生了blur
或keypress
事件,並確保處理程序不會運行兩次。
您還可以執行以下操作:
var doo = function(e){ console.log("do..."); }
$('#wmd-input').bind('blur', doo);
$('#wmd-input').bind('keypress focus', function(e) {
$('#wmd-input').off('blur');
if (e.keyCode == 13) {
doo(e);
} else
$('#wmd-input').bind('blur', doo);
});
當焦點發生時,它確實再次綁定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.