我的输入值检测在 Chrome 中运行良好,但在 Internet Explorer 中,如果用户键入回车键,则不会触发“更改”事件。我怎样才能让它适用于两种浏览器,并防止事件在 Chrome 中被触发两次?
HTML
<input type="text" class="price">
<h2></h2>
jQuery
var $input = $('.price');
$input.on('change', function(e) {
$('h2').text($(this).val());
//do other calculation
}).on('keyup', function(e) {
if(e.which != 13) return;
e.preventDefault();
$(this).trigger('change');
})
最佳答案
这个问题很久了,不知道jQuery为什么不自动处理。如果浏览器支持 onchange 的回车键,似乎没有任何方法可以避免触发两个事件,所以您只需要解决它:
$input.on('focus', function(e) {
this.calculationDone = false;
}).on('change', function(e) {
if (!this.calculationDone) {
calculationDone = true;
$('h2').text($(this).val());
console.log('done');
//do other calculation
}
}).on('keyup', function(e) {
if(e.which != 13) return;
e.preventDefault();
$(this).trigger('change');
})
关于javascript - jQuery 更改事件未正确触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33385619/