javascript - IE兼容問題 動態(tài)生成的節(jié)點IE瀏覽器無法觸發(fā),求助
問題描述
代碼很簡單,就是動態(tài)生成input標簽,來實現(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é)點,所以你可以在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 而不是使用標準方法addEventListener。
回答3:IE8及以下沒有addEventListener方法 可用attachEvent()方法監(jiān)聽事件 要注意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. javascript - 求助canvas繪制半透明的馬賽克?2. php多任務倒計時求助3. javascript - 求助Angular 1 在$scope里向對象屬性賦值不起效的原因(作用域問題),無盡感激!4. 【求助大神】PHP初學者的學習規(guī)劃和視頻課程推薦(詳細一些)5. javascript - 關于addEventListener和attachEvent的兼容寫法疑問,求助!6. javascript - 關于向java后臺上傳base64位字符串的圖片數(shù)據(jù),求助7. 數(shù)據(jù)庫 - Mysql的存儲過程真的是個坑!求助下面的存儲過程哪里錯啦,實在是找不到哪里的問題了。8. 老哥們求助啊9. 緊急求助-我們的一位同事突然離職,需要一個后端的同事,項目才能進行,停滯了,那位可以幫幫忙?10. php安裝lpsolve 擴展求助
