【发布时间】:2018-01-13 01:53:21
【问题描述】:
我正在修复网站上的跨浏览器错误,并发现其原因是 jQuery Click & Change 事件在不同时间触发,具体取决于您的浏览器。
例如,在 Chrome 和 Firefox 上,Click 事件在更改事件之前触发。在 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>
如果您运行 sn-p 并单击单选按钮,您将在控制台中看到被触发的事件的顺序。
我已经在 Chrome 60、FireFox 54、Safari 10.1 和 Internet Explorer 11 上进行了测试
【问题讨论】:
标签: javascript jquery cross-browser jquery-events