jQuery更改事件未正确触发

jQuery change event is not triggered correctly

本文关键字:事件 jQuery      更新时间:2023-09-26

我的输入值检测在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');
    })