Home  >  Article  >  Web Front-end  >  js change,propertychange,input事件小议_javascript技巧

js change,propertychange,input事件小议_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:58:051249browse
https://github.com/mootools/mootools-core/issues/2170

这个问题来自IE(LTE8)中对checkbox和radio change事件的实现问题,在IE(LTE8)中测试下来,当你点击一个checkbox或者radio,它的change事件是不会立即触发,除非你让它失去焦点,而在其他标准浏览器中(包括IE9),是点击后立即触发change事件的,这的确是个蛋疼的问题,说到解决方法,倒也比较容易,用IE(LTE8)中元素特有的propertychange事件来处理(IE9已经没这玩意儿了),就能避免上述问题,如:

复制代码 代码如下:

checkEl.attachEvent('onpropertychange', function() {
console.log('hey man, I am changed');
});

但是这样就认为解决了,是不充分的,因为像checkEl.setAttribute('data-value', 'god')这样的操作也会触发其propertychange事件,所以我们需要用其event.propertyName来判断下,如:

复制代码 代码如下:

checkEl.attachEvent('onpropertychange', function() {
if(window.event.propertyName == 'checked')
console.log('blah blah blah...');
});

这样算是可以了。由此展开我又测试了下select,其change事件的表现在不同浏览器中一致,没有出现非要先失去焦点的情况。我又测试了下input[type="text"],它的change事件是我们所熟悉的,要失去焦点才会触发,那么当我们想让它一输入东西就立即触发呢,参考之前的例子在IE(LTE8)中,我们可以用propertychange来实现,只不过propertyName的条件变成‘value'而已。在其他标准浏览器中(包括IE9),我们可以用HTML5中的一个标准事件input, 如:

复制代码 代码如下:

inputEl.addEventListener('input', function(event) {
console.log('input event fired');
}, false);

这样我们的每一次输入都会触发此事件,有人会说为什么不用keyup来监听一下, 这里有篇文章(原文链接)对此问题进行了阐述,感兴趣的也可以读读。
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