In a recent project, there is such a functional point: there is a checkbox on the page. When the user selects or deselects the checkbox, a jsonp request will be sent to the background. The implementation at that time was to add an onchange event to this checkbox, but the result was unexpected. For this reason, I conducted an in-depth study and found that the onchange event had the following problems in its performance under IE and FF.
Question ①: Under FF, when the selected state of the checkbox is changed, the onchange event will be triggered immediately. However, when changing the selected status of the checkbox under IE, the onchange event will not be triggered immediately. Instead, the event will be triggered after the checkbox loses focus.
In order to solve this problem, I added this.blur() statement to the onclick event of the checkbox. This is because the onclick event is executed before the onchange event, so adding this.blur() to the Onclick event causes the checkbox to lose The focus will immediately fire the onchange event. But then, we encountered a second problem.
Problem ②: When the onclick event and this.blur are used at the same time, an error will be reported under IE.
After searching for some information on the Internet, I finally discovered the onpropertychange event. This event will not be triggered under FF. Under IE, it will start immediately when the selection status of the checkbox changes. So, the final solution was reached: under IE, bind the onpropertychange event to the checkbox, and under FF, bind the onchange event to it.
The specific code implementation is as follows:
Copy the code code as follows:
var ua=navigator.userAgent.toLowerCase();
vars=null;
var browser={
msie:(s=ua.match(/msie/s*([/d/.]+)/))?s[1]:false,
firefox:(s=ua.match(/firefox//([/d/.]+)/))?s[1]:false,
chrome:(s=ua.match(/chrome//([/d/.]+)/))?s[1]:false,
opera:(s=ua.match(/opera.([/d/.]+)/))?s[1]:false,
safari:(s=ua.match(/varsion//([/d/.]+).*safari/))?s[1]:false
};
if(browser.msie){//If it is IE browser
checkbox.onpropertychange=function(){
//do someting
}
}
else{
checkbox.onchange=function(){
//do something
}
}