javascript - IE兼容問題 動態(tài)生成的節(jié)點(diǎn)IE瀏覽器無法觸發(fā),求助
問題描述
代碼很簡單,就是動態(tài)生成input標(biāo)簽,來實(shí)現(xiàn)change事件無法處理相同文件。在chrome,firefox中都有效,但在ie瀏覽器中無法觸發(fā)打印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()不能操作文檔中沒有的節(jié)點(diǎn),所以你可以在click()前添加下面的語句
document.body.appendChild( input );input.style.display = ’none’;input.click();
要想兼容ie9之前用attachEvent而不是addEventListener。還有ie9之前不兼容getElementsByClassName
回答2:為什么 button 使用了 .onclick,后面的 input 卻用了 .addEventListener 呢?
在 addEventListener 文檔的 傳統(tǒng)的 Internet Explorer 及其 attachEvent 方法 有說明:
對于 Internet Explorer 來說,在IE 9之前,你必須使用 attachEvent 而不是使用標(biāo)準(zhǔn)方法addEventListener。
回答3:IE8及以下沒有addEventListener方法 可用attachEvent()方法監(jiān)聽事件 要注意attachEvent回調(diào)中的this指向的是window哦
回答4:用下面這個(gè)來綁定事件
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');});
相關(guān)文章:
1. javascript - vue生成一維碼?求助!!!!!急2. ueditor上傳服務(wù)器提示后端配置項(xiàng)沒有正常加載,求助!!!!!3. mysql - iOS 360度瀏覽車模,點(diǎn)擊零配件可替換模型內(nèi)的零件,求助4. python - 編碼問題求助5. javascript - 關(guān)于向java后臺上傳base64位字符串的圖片數(shù)據(jù),求助6. css - 求助:還原網(wǎng)頁的過程中遇到的一個(gè)奇怪的問題?7. 調(diào)用百度翻譯API,在JAVA項(xiàng)目可以翻譯,在android中卻不行。求助8. mysql建表索引問題求助9. python在list相加 求助10. php安裝lpsolve 擴(kuò)展求助
