javascript - IE兼容問題 動態生成的節點IE瀏覽器無法觸發,求助
問題描述
代碼很簡單,就是動態生成input標簽,來實現change事件無法處理相同文件。在chrome,firefox中都有效,但在ie瀏覽器中無法觸發打印3.求助!!!
var button=document.getElementsByClassName(’button’)[0];var imgBox=document.getElementsByClassName(’imgBox’)[0];button.onclick=function(){ inputImg();}function inputImg(){ var input=document.createElement(’input’); input.type=’file’; input.addEventListener(’change’,function(e){console.log(3); });input.click();}
問題解答
回答1:ie下click()不能操作文檔中沒有的節點,所以你可以在click()前添加下面的語句
document.body.appendChild( input );input.style.display = ’none’;input.click();
要想兼容ie9之前用attachEvent而不是addEventListener。還有ie9之前不兼容getElementsByClassName
回答2:為什么 button 使用了 .onclick,后面的 input 卻用了 .addEventListener 呢?
在 addEventListener 文檔的 傳統的 Internet Explorer 及其 attachEvent 方法 有說明:
對于 Internet Explorer 來說,在IE 9之前,你必須使用 attachEvent 而不是使用標準方法addEventListener。
回答3:IE8及以下沒有addEventListener方法 可用attachEvent()方法監聽事件 要注意attachEvent回調中的this指向的是window哦
回答4:用下面這個來綁定事件
var addEvent = function(elem, type, handler){ if(window.addEventListener){addEvent = function(elem, type, handler){ elem.addEventListener(type, handler, false);}; }else if(window.attachEvent){addEvent = function(elem, type, handler){ elem.attachEvent(’on’ + type, handler);}; } addEvent(elem, type, handler);};addEvent(input, 'change', function(e){ alert('changed');});
相關文章:
1. PHP求助,求幫忙謝謝各位2. list - python 求助3. python - 求助,ValueError: View function did not return a response4. javascript - 求助canvas繪制半透明的馬賽克?5. python在list相加 求助6. android-studio - 一直無法下載android studio的 安卓模擬器求助7. python - scrapy pipeline報錯求助8. 老哥們求助啊9. python3.x - 求助python下高效且支持大數據量的database2excel方案10. javascript - 關于事件綁定時指定this的問題,求助
