search

Home  >  Q&A  >  body text

javascript - IE compatibility issue. Dynamically generated nodes cannot be triggered by IE browser. Please help.

The code is very simple, it is to dynamically generate input tags to realize that the change event cannot process the same file. It works in Chrome and Firefox, but printing cannot be triggered in IE browser 3. Help! ! !

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();
}
为情所困为情所困2752 days ago876

reply all(4)I'll reply

  • 为情所困

    为情所困2017-06-26 10:58:54

    ieunder click() cannot operate nodes that are not in the document, so you can add the following statement before click()

    document.body.appendChild( input );
    input.style.display = 'none';
    input.click();

    To be compatible with ie9, use attachEvent instead of addEventListener.
    Also ie9 was not compatible before getElementsByClassName

    reply
    0
  • 学习ing

    学习ing2017-06-26 10:58:54

    Why does button use .onclick, but the following input uses .addEventListener?

    In the addEventListener documentation, traditional Internet Explorer and its attachEvent method are explained:

    For Internet Explorer, prior to IE 9, you had to use attachEvent instead of using the standard method
    addEventListener.

    reply
    0
  • 習慣沉默

    習慣沉默2017-06-26 10:58:54

    IE8 and below do not have the addEventListener method. You can use the attachEvent() method to listen for events. Please note that this in the attachEvent callback points to the window

    reply
    0
  • 大家讲道理

    大家讲道理2017-06-26 10:58:54

    Use the following to bind the event

    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");
    });
    

    reply
    0
  • Cancelreply