2017-08-05 39 views
2

我正在修復網站上的跨瀏覽器錯誤,並發現它的原因是jQuery點擊&更改事件fire在不同的時間取決於你的瀏覽器。爲什麼jQuery點擊和更改事件在Chrome瀏覽器與Safari或IE上的不同時間點火

例如在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"> 
 
\t <input value="10" name="foobar" checked="checked" data-name="foo" id="option_1" type="radio"> 
 
\t <span>Foo</span> 
 
     </label> 
 
    </li> 
 
    <li> 
 
     <label for="option_2"> 
 
\t <input value="12" name="foobar" data-name="bar" id="option_2" type="radio"> 
 
\t <span>Bar</span> 
 
     </label> 
 
    </li> 
 
    </ul> 
 
    <button onclick="productAddToCartForm.submit(this)" title="Add to Basket" type="button">Add to Basket</button> 
 
</form>

如果您運行的片段,並點擊單選按鈕,你就會在控制檯中看到的一個例子。

我已經在Chrome 60,火狐54,Safari瀏覽器10.1和Internet Explorer測試11

回答

2

一種選擇是定義一個自定義事件,並使用.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"> 
 
\t <input checked="checked" data-name="foo" id="option_1" name="foobar" type="radio" value="10"> 
 
\t <span>Foo</span> 
 
     </label> 
 
    </li> 
 
    <li> 
 
     <label for="option_2"> 
 
\t <input data-name="bar" id="option_2" name="foobar" type="radio" value="12"> 
 
\t <span>Bar</span> 
 
     </label> 
 
    </li> 
 
    </ul> 
 
    <button title="Add to Basket" type="button">Add to Basket</button> 
 
</form>

相關問題