简体   繁体   中英

click event not firing in IE11

I have this js file:

function fireClick(node){
    if ( document.createEvent ) {
        var evt = document.createEvent('MouseEvents');
        evt.initEvent('click', true, false);
        node.dispatchEvent(evt);
    } else if( document.createEventObject ) {
        node.fireEvent('onclick') ;
    } else if (typeof node.onclick == 'function' ) {
        node.onclick();
    }
}

function selectAvatar()
{

    var fileSelector = document.createElement('input');
    fileSelector.setAttribute('type', 'file');
    fileSelector.setAttribute('accept', "image/gif, image/jpeg");



    fileSelector.onchange = function(event) {
        var fileList = fileSelector.files;
        //alert(fileList.length);
        if (fileList.length==0) return;
        reader.readAsDataURL(fileList[0]);
    }
    var reader = new FileReader();

    reader.onload = function(e) {
        var dataURL = reader.result;
        //alert(dataURL);
        var container = document.getElementById("avatart-container-div");
        var backgroundIMgString = 'url("'+dataURL+'")';
        container.style.backgroundImage=backgroundIMgString;
    }
    fireClick(fileSelector);
}

which is supposed to open programatically a file picker to select an imgae. While this works on FF and chrome, this does NOT work on IE (11 is my version). The picker itself doesn't show up. Tried debugging line by line but everything seems fine (no errors or exceptions). Any have an idea what might be the problem?

Taken from the comments:

You are actually only creating the element, without adding it to the DOM. You can add it to the DOM with: document.body.appendChild(fileSelector);

And in the selectAvatar function:

function selectAvatar()
{

    var fileSelector = document.createElement('input');
    fileSelector.setAttribute('type', 'file');
    fileSelector.setAttribute('accept', "image/gif, image/jpeg");

    document.body.appendChild(fileSelector);

    // do stuff
}

Also здрасти

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM