按键一次后无法解除按键事件的绑定
我创建了一个输入字段,按下回车键 (13) 时会提交一个简单的字段。如果您第一次按下该键,该代码会起作用,但在我刷新页面之前,该代码将不再起作用。我试图解除该事件的绑定,但没有任何反应。
$(function () {
$('#new_list').bind('keypress', function (e) {
if(e.which === 13) {
console.log('enter pressed');
var nl_val = {};
nl_val['list_name'] = $('#new_list').val();
$.post('/lists/js_new_list',nl_val,function(str) {
if(str == 'error') {
$('#info').css({'color':'red'})
.fadeIn(1000)
.text('There was an error.')
.fadeOut(1000);
} else {
$('#new_list').hide().val('');
$('#info').css({'color':'#00620C'})
.fadeIn(1000)
.text('List created.')
.fadeOut(1000);
js_refresh_lists();
}
});
$('#new_list').unbind("keypress");
} // UPDATE: this is the if(e.which === 13) end
});
});
function js_refresh_lists() {
var id = list_id();
console.log('refreshing list');
$('#lists').load('/lists/js_refresh_lists');
}
更新:我希望用户能够添加另一个列表(我的情况),而无需刷新页面以使按键事件再次工作。目前,正如本文顶部提到的,它仅在第一次添加新列表时起作用,之后回车键不起作用。
谁能弄清楚为什么密钥解除绑定吗?
干杯
I've created an input field that submits a simple field when the enter key (13) is pressed. The code works if you pressed the key the first time but then it never works again until i refresh the page. I'm trying to unbind the event but nothing happens.
$(function () {
$('#new_list').bind('keypress', function (e) {
if(e.which === 13) {
console.log('enter pressed');
var nl_val = {};
nl_val['list_name'] = $('#new_list').val();
$.post('/lists/js_new_list',nl_val,function(str) {
if(str == 'error') {
$('#info').css({'color':'red'})
.fadeIn(1000)
.text('There was an error.')
.fadeOut(1000);
} else {
$('#new_list').hide().val('');
$('#info').css({'color':'#00620C'})
.fadeIn(1000)
.text('List created.')
.fadeOut(1000);
js_refresh_lists();
}
});
$('#new_list').unbind("keypress");
} // UPDATE: this is the if(e.which === 13) end
});
});
function js_refresh_lists() {
var id = list_id();
console.log('refreshing list');
$('#lists').load('/lists/js_refresh_lists');
}
UPDATE: I want the user to be able to add another list (my case) without the need to refresh the page to get the keypress event working again. At the moment as mentioned at the top of this post, it only works the first time a new list is added, after that the enter key does nothing.
Can anyone figure out why the key is unbinding?
Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你的问题是,在第一次成功按键后,你用 js_refresh_lists() 刷新表单,它将你的 #new_list 字段替换为一个新字段,该字段没有按键绑定。
在上述情况下,您有 2 个选择:
I think your problem is that after the first successful keypress you refresh your form with js_refresh_lists() which replaces your #new_list field with a new one, which does not have the keypress bind on it.
In the above case you have 2 options: