jQuery .click() does not work in Safari

2019-03-20 19:11发布

问题:

I have seen several similar posts with solutions that seemed to have worked for those people, but I CANNOT get this to work.

I am using http://tutorialzine.com/2013/05/mini-ajax-file-upload-form/ in my project. It works PERFECTLY, in all browsers, except in Safari the "BROWSE" button does not open a file dialog. The following code exists in script.js (which is included for the plugin to work):

$('#drop a').click(function(){
    // Simulate a click on the file input button
    // to show the file browser dialog
    $(this).parent().find('input').click();
});

The .click() does not fire in Safari. I have tried the solution as per jQuery .click() works on every browser but Safari and implemented

 $('#drop a').click(function(){
    var a = $(this).parent().find('input');
    var evObj = document.createEvent('MouseEvents');
    evObj.initMouseEvent('click', true, true, window);
    a.dispatchEvent(evObj);
});

But then I get the error that dispatchEvent is not a function. I then did some research on this, and tried the jQuery.noConflict() route, but this did not resolve the error. Also, I use a LOT of jQuery in my main file and I cannot have the noConflict() mode activated for the entire page. There is also no reason that the jQuery should be conflicting with anything as I am only using jQuery and normal javascript and I am not using anything like prototype or angular. Does anybody know of another way to simulate a click in Safari?

UPDATE: Just FYI, I have added an alert('test') in the mentioned function (which triggers when "BROWSE" is clicked), and I do get the alert in Safari, but it is not simulating the click of the file input element, i.e: it is not openening the file dialog.

回答1:

The second section of code in my original question turned out to work, except for 2 things.

1) The method does not like jQuery, so instead of

var a = $(this).parent().find('input')[0];

I assigned an ID to my file input and instead called

var a = document.getElementById('upload_select');

2) Safari blatantly ignores this if the input is hidden (display:none;), which is was, so instead I made the input font-size = 1px; and opacity = 0.

Implementing these two changes got the code working.



回答2:

You need to read that answer more closely. :-)

dispatchEvent is a function on the DOM element, not the jQuery object. You're trying to call it on the jQuery object. So:

$('#drop a').click(function(){
    var a = $(this).parent().find('input')[0];
    // Change here -----------------------^^^
    var evObj = document.createEvent('MouseEvents');
    evObj.initMouseEvent('click', true, true, window);
    a.dispatchEvent(evObj);
});

Using the [0] on the jQuery object gives you the first DOM object in the jQuery object, or undefined if the jQuery object is empty.