调用input的点击事件;不能在Safari中工作
calling click event of input doesn't work in Safari
我有一个输入,文件类型,带有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>
相关文章:
- jQuery Datepicker可以在Safari中工作,但不能在FF或Chrome中工作
- 为什么我的JavaScript在Safari上的严格模式下不能正常工作
- jQuery$.post可以在chrome、safari中工作,但不能在FF中工作(声明成功回调函数未定义)
- RGB 到 HEX JavaScript 函数在 Chrome 中工作,但不能在 Firefox 或 Safari 中工
- 我的简单Javascript代码可以在Safari上运行,但不能在Chrome、Firefox或Opera上运行
- Date.prototype.get日期;不能在Safari中工作
- JQuery图像大小计算没有'不能在Chrome/Safari中工作
- JavaScript倒计时;不能在Safari中工作
- 为什么这个html5音频不能在chrome上工作,但在safari上工作得很好
- Javascript可以在Safari上运行,但不能在任何其他浏览器上运行
- Javascript在Safari中工作,但不能在Chrome或Firefox中工作
- jQuery在Chrome和Safari中工作,但不能在Firefox或IE中工作
- 不能在一个页面上编写cookie,Safari iOS
- 为什么 $(document).blur() 和 $(document).focus() 不能与 Safari 或 Ch
- Ajax在Chrome / Safari中提交作品,但不能在Firefox / IE中提交作品
- jQuery scrollTop()没有'不能在Safari中工作
- 谷歌地图地理编码PHP可以在IE中工作,但不能在Chrome/mobile、Edge或Safari/mobile中工作.
- JavaScript代码只能在Chrome中使用,但不能在Firefox、IE、Opera和Safari中使用
- Javascript倒计时;不能在Safari或IE中工作
- 调用input的点击事件;不能在Safari中工作