为什么 jQuery 单击和更改事件在 Chrome 与 Safari 或 IE 上的不同时间触发

Why jQuery click & change events firing at different times on Chrome vs Safari or IE

我正在修复一个网站上的跨浏览器错误,发现原因是 jQuery Click & Change 事件会在不同的时间触发,具体取决于您的浏览器。

例如在 Chrome 和 Firefox 上,Click 事件在 change 事件之前触发。而在 Safari 或 IE 11 上则相反。

我原以为使用 jQuery 不会发生这种情况,因为 jQuery 以经过良好的跨浏览器兼容性测试而闻名。

无论如何,是否可以使用 jQuery/JavaScript 确保 .click 函数中的代码始终在 .change 函数中的代码之前执行,而不管浏览器如何?
我意识到,通过下面的示例,我可以将所有内容都放在一个事件中,但我想知道我所问的是否可行。

代码示例如下:

var $input = $('input[name="foobar"]');
$input.click(function() {
  console.log( "Click event called for input with value " + $(this).val() );
  });
$input.change(function() {
  console.log( "Change event called for input with value " + $(this).val() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="http://example.com/checkout/add/" id="product_addtocart_form" method="post" name="product_addtocart_form">
  <ul>
    <li>
      <label for="option_1">
  <input value="10" name="foobar" checked="checked" data-name="foo" id="option_1" type="radio">
  <span>Foo</span>
      </label>
    </li>
    <li>
      <label for="option_2">
 <input value="12" name="foobar" data-name="bar" id="option_2" type="radio">
 <span>Bar</span>
      </label>
    </li>
  </ul>
  <button onclick="productAddToCartForm.submit(this)" title="Add to Basket" type="button">Add to Basket</button>
</form>

如果您 运行 片段并单击单选按钮,您将在控制台中看到触发事件的顺序。

我已经在 Chrome 60、FireFox 54、Safari 10.1 和 Internet Explorer 11

上进行了测试

一个选项是定义一个自定义事件并使用 .trigger()click 事件处理程序

中分派该事件

var $input = jQuery('input[name="foobar"]');
$input.on("click", function() {
  console.log( "Click event called for option with value " + jQuery(this).val() );
  $(this).trigger("customChange", ["customChange called from click handler"])
  });
$input.on("customChange", function(e, customChangeData) {
  console.log( "Change event called for option with value " + jQuery(this).val(), customChangeData );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="http://example.com/checkout/add/" id="product_addtocart_form" method="post" name="product_addtocart_form">
  <ul>
    <li>
      <label for="option_1">
  <input checked="checked" data-name="foo" id="option_1" name="foobar" type="radio" value="10">
  <span>Foo</span>
      </label>
    </li>
    <li>
      <label for="option_2">
 <input data-name="bar" id="option_2" name="foobar" type="radio" value="12">
 <span>Bar</span>
      </label>
    </li>
  </ul>
  <button title="Add to Basket" type="button">Add to Basket</button>
</form>