In JavaScript can I make a “click” event fire programmatically for a file input element?

前端 未结 28 1336
囚心锁ツ
囚心锁ツ 2020-11-21 06:29

I\'d like to make a click event fire on an tag programmatically.

Just calling click() doesn\'t seem to do anything or at lea

28条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 06:53

    it's not impossible:

    var evObj = document.createEvent('MouseEvents');
    evObj.initMouseEvent('click', true, true, window);  
    setTimeout(function(){ document.getElementById('input_field_id').dispatchEvent(evObj); },100);
    

    But somehow it works only if this is in a function which was called via a click-event.

    So you might have following setup:

    html:

    Click here to open image chooser

    JavaScript:

        function openFileChooser() {
          var evObj = document.createEvent('MouseEvents');
          evObj.initMouseEvent('click', true, true, window);  
          setTimeout(function()
          { 
            document.getElementById('input_img').dispatchEvent(evObj);      
          },100);      
        }
    

提交回复
热议问题