Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

javascript - jQuery .click() works on every browser but Safari

I have a piece of JavaScript that dynamically creates an A tag inside of an existing div and then calls the jQuery function "click" on it. This works as intended in all browsers except Safari.

Safari returns the following error:

'undefined' is not a function (evaluating '$('.shell a')[0].click()')

Any ideas on what I'm doing wrong or why this doesn't work in Safari and how to get it to work (or one piece of code that works in all browsers) I've tried using .trigger("click") as well and it gives the same error.

JavaScript

function writeAndClickLink(url) {

    $('.shell').html('<a href="' + url + '"></a>');
    $('.shell a')[0].click();
}

and in the HTML:

<div class="shell"></div>

The reason I'm doing it this weird way is the function is called from a Flash site to open a twitter window where I am giving a reward for tweeting. This so far has been the only way I could get the "tweet" event to bind to the window. If I open the window any other way (window.open for example) it doesn't capture the bound event that lets me know they actually completed the tweet.

The flow is something like:

  • User clicks tweet button in flash
  • Flash calls javascript function to dynamically write href and "click" it
  • Twitter window opens
  • User successfully tweets
  • Tweet event is captured and updates flash with success
  • Content is unlocked in flash
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
var a = $('.shell a')[0];
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('click', true, true, window);
a.dispatchEvent(evObj);

See http://www.howtocreate.co.uk/tutorials/javascript/domevents (search for "Manually firing events").


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...