admin管理员组

文章数量:1417107

I need to simulate a click on a button using jquery.

Regular Javascript MouseEvents (mousedown and mouseup) do work, but I want jquery.

I have the div in a jquery object: (just a reference)

it was defined like

var $button = $(document.getElementById("iframe")...);

$button -> <div id="1" class="2" role = "button"><b>Action</b></div>

I've tried with $button.click() and $button.trigger('click') but both don't work.

I've read this, but provides no answer to this question.

I need to simulate a click on a button using jquery.

Regular Javascript MouseEvents (mousedown and mouseup) do work, but I want jquery.

I have the div in a jquery object: (just a reference)

it was defined like

var $button = $(document.getElementById("iframe")...);

$button -> <div id="1" class="2" role = "button"><b>Action</b></div>

I've tried with $button.click() and $button.trigger('click') but both don't work.

I've read this, but provides no answer to this question.

Share Improve this question edited May 23, 2017 at 12:19 CommunityBot 11 silver badge asked Aug 1, 2012 at 18:05 jacktradesjacktrades 7,40214 gold badges59 silver badges84 bronze badges 5
  • Can you post more code? $('#foo').trigger('click'); should work... – Giovanni B Commented Aug 1, 2012 at 18:06
  • Need more context on your javascript and HTML. – Mike Brant Commented Aug 1, 2012 at 18:07
  • $('#foo').click() should also work – PitaJ Commented Aug 1, 2012 at 18:08
  • Now, I'm assuming that your $button was defined earlier as var $button = $('button'), correct? In that case you trigger a click just like you tried with the trigger, or simply $('button').click(); – hndcrftd Commented Aug 1, 2012 at 18:09
  • No it was not like this, it took a division of an existing HTML page, that performs an action outside of my script. – jacktrades Commented Aug 1, 2012 at 18:30
Add a ment  | 

1 Answer 1

Reset to default 6

Try this:

var e = document.createEvent("MouseEvents");
e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
$button[0].dispatchEvent(e);

本文标签: javascriptJquery simulate a click on ltdiv rolebuttongtStack Overflow