我有一个输入,文件类型,带有 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();
控制台没有错误。我试过 this但什么都没有。
$(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>
关于javascript - 调用输入的点击事件在 Safari 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26501221/