Home  >  Article  >  Web Front-end  >  关于onchange事件在IE和FF下的表现及解决方法_javascript技巧

关于onchange事件在IE和FF下的表现及解决方法_javascript技巧

WBOY
WBOYOriginal
2016-05-16 16:56:211118browse

在最近做的一个项目中,有这么一个功能点:页面上有一个checkbox,当用户选择或者取消选择该checkbox时会向后台发一个jsonp请求。当时的实现是为这个checkbox添加一个onchange事件,但结果却出人意料,为此,我深入的研究了一下,发现了onchange事件在IE和FF下的表现存在着以下问题。

问题①:在FF下,当改变checkbox的选中状态时,会马上触发onchange事件。但在IE下改变checkbox的选中状态时,并不会马上出发onchange事件,而是需要等待checbox失去焦点时该事件才会出发。

为了解决这个问题,我在checkbox的onclick事件里添加了this.blur()这条语句,这是由于onclick事件是在onchange事件之前执行的,因而在Onclick事件中添加this.blur()使checkbox失去焦点便马上会出发onchange事件。可如此一来,又遇到了第二个问题。

问题②:当onclick事件和this.blur同时使用时,在IE下会报错。

在网上查找了一些资料,终于发现了onpropertychange这个事件。该事件在FF下是不会触发的。而在IE下,当checkbox的选择状态改变时马上会出发。于是,得出了最终的解决方案:在IE下,为checkbox绑定onpropertychange事件,而在FF下,为其绑定onchange事件。

具体代码实现如下:

复制代码 代码如下:

var ua=navigator.userAgent.toLowerCase();
var s=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){//若为IE浏览器
    checkbox.onpropertychange=function(){
         //do someting
    }
}
else{
    checkbox.onchange=function(){
        //do something
    }
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn