[英]preventDefault() for keypress cancels change event
In the code snippet below, I'm trying to prevent the user from entering new lines into a <textarea>
by using preventDefault()
.在下面的代码片段中,我试图通过使用
preventDefault()
来阻止用户在<textarea>
中输入新行。 Instead of entering new lines, I want the enter key to trigger the blur event.我不想输入新行,而是希望输入键触发模糊事件。 However, the code below is bypassing the change event after the user changes the text within the
<textarea>
and then hits enter.但是,下面的代码在用户更改
<textarea>
中的文本然后点击回车后绕过了更改事件。 How can I ensure that the change event always fires when the value of the text is changed?如何确保更改文本的值时始终触发更改事件?
$('textarea')
.keypress(function (event) {
if (event.which == '13') {//13 = Enter
event.preventDefault();
$(this).blur();
}
})
.change(function() {// THIS DOES NOT FIRE IF USER PRESSES ENTER
alert('change event');
})
.blur(function() {
console.log('blur event');
});//end: blur()
Looks like it is a problem with the event ordering .看起来这是事件排序的问题。 In IE
change
event is fired first then blur
event is fired but in Firefox and Chrome it is the opposite.在 IE 中,首先触发
change
事件,然后触发blur
事件,但在 Firefox 和 Chrome 中则相反。 So when you fire blur()
event manually in Firefox and Chrome it causes the focus
event to fire, but in IE it won't.因此,当您在 Firefox 和 Chrome 中手动触发
blur()
事件时,它会触发focus
事件,但在 IE 中则不会。
Just trigger the change event manually, the same way you trigger the blur event.只需手动触发 change 事件,就像触发 blur 事件一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.