gpt4 book ai didi

javascript - jQuery 更改事件未正确触发

转载 作者:太空宇宙 更新时间:2023-11-04 13:28:17 26 4
gpt4 key购买 nike

我的输入值检测在 Chrome 中运行良好,但在 Internet Explorer 中,如果用户键入回车键,则不会触发“更改”事件。我怎样才能让它适用于两种浏览器,并防止事件在 Chrome 中被触发两次?

js fiddel

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com