【问题标题】:calling click event of input doesn't work in Safari调用输入的点击事件在 Safari 中不起作用
【发布时间】:2021-02-03 05:04:13
【问题描述】:

我有一个输入,文件类型,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>


   

【问题讨论】:

  • 您使用的是哪个版本的 Safari?
  • @Sprotenwels 5.1.7(7534.57.2)
  • 不使用display: none隐藏是否有效?
  • @dfsq 我刚刚测试过。没有区别
  • 如果输入类型文件未隐藏并且 click() 在用户交互之外调用(例如在 onclick 处理程序等内部),则 Safari 中的输入类型文件上的 Click 事件将起作用。

标签: javascript jquery html safari


【解决方案1】:

问题完全解决了。重点是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>

【讨论】:

  • 可见性不是它起作用的原因,而是它被点击事件调用的事实。
【解决方案2】:

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

 $('#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>

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-13
  • 2023-04-01
  • 2014-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多