调用input的点击事件;不能在Safari中工作

calling click event of input doesn't work in Safari

本文关键字:不能 Safari 工作 事件 input 调用      更新时间:2023-09-26

我有一个输入,文件类型,带有display:none,还有一个按钮。单击该按钮后,应该触发输入的事件。在IE、Chrome和Firefox中,它可以工作,但在Safari中不行!

var elem=$('<input id="ajxAttachFiles" name="fileUpload" type="file" style="display: none;"/>');
    if($("#ajxAttachFiles").length==0){
        elem.prependTo(".ChProgress");
    }
$("#ajxAttachFiles").click();

控制台中没有错误。我试过了,但什么也没试。

$(document).ready(function(){
        $("#btn").on('click',function(){
          $("#ajxAttachFiles")[0].click();
        });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input id="ajxAttachFiles" type="file" style="display:none;">
<button id="btn" type="button">Click me!</button>
   

问题已完全解决。点是input[type=file]的元素,不能是display: none。看看下面的例子:

function click(el) {
  // Simulate click on the element.
  var evt = document.createEvent('Event');
  evt.initEvent('click', true, true);
  el.dispatchEvent(evt);
}
document.querySelector('#selectFile').addEventListener('click', function(e) {
  var fileInput = document.querySelector('#inputFile');
  //click(fileInput); // Simulate the click with a custom event.
  fileInput.click(); // Or, use the native click() of the file input.
}, false);
<input id="inputFile" type="file" name="file" style="visibility:hidden; width:0; height:0">
<button id="selectFile">Select</button>

在DOM元素而不是jQuery对象上触发点击事件。这应该适用于所有浏览器。

 $('#ajxAttachFiles')[0].click();

或者:

document.getElementById('ajxAttachFiles').dispatchEvent( new Event('click') );
//for IE < 9 use microsoft's document.createEventObject 

var elem=$('<input id="ajxAttachFiles" name="fileUpload" type="file" style="display: none;"/>');
    if($("#ajxAttachFiles").length==0){
        elem.prependTo(".ChProgress");
    }
$("#ajxAttachFiles").on('click',function() {
  alert( 'click triggered' );
});
$("#ajxAttachFiles")[0].click();
//an alternative:
var event = new Event('click');
document.getElementById('ajxAttachFiles').dispatchEvent(event);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ChProgress">Will be added here</div>