javascript - IE compatibility issue. Dynamically generated nodes cannot be triggered by IE browser. Please help.
为情所困
为情所困 2017-06-26 10:56:54
0
4
864

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

reply all(4)
为情所困

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

学习ing

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.

習慣沉默

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

大家讲道理

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");
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template