我正在修复网站上的跨浏览器错误,并且发现其原因是jQuery Click&Change事件在不同时间触发,具体取决于您的浏览器。
例如,在Chrome和Firefox上,Click事件在change事件之前触发。在Safari或IE 11上,反之亦然。
我曾希望通过使用jQuery不会发生这种情况,因为众所周知jQuery已通过跨浏览器兼容性的良好测试。
无论如何,是否可以使用jQuery / JavaScript确保始终在.change函数中的代码之前执行.click函数中的代码,而不考虑浏览器是什么?
我意识到,使用下面的示例,我可以将所有内容都放入一个事件中,但是我想知道我要问的事情是否可能。
这是代码示例:
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>