Jquery triggering a click

我的梦境 提交于 2020-01-03 06:06:08

问题


I've been trying to use jquery to trigger a click.

I've discovered that triggered clicks, like this: $(button).trigger('click'); do not follow hrefs. I've been trying to make an ajax submission by triggering the submit button, but no go.

I know I can submit directly. But is there any way of triggering the button? Thanks.


回答1:


jQuery does not trigger the native "click" on A elements on purpose. I don't know why.

But you can use the technique they use to trigger the link yourself:

$link[0].click(); // extract the native DOM element and trigger the click

This is untested but it is extracted from jQuery source code and should work.




回答2:


I don't see why you would need to do that. Maybe you want the label of the submit button to be submitted with the form (so your server code knows what button is pressed). In that case, you can do something like this:

var $form = $("form"); // your form
var $button = $(":submit",$form); // your button
var $hidden = $("<input type='hidden' />");

$hidden.attr("name",$button.attr("name"));
$hidden.val($button.val());

$form.append($hidden);
$form.submit();

I'm sure this can be optimized, but it will work (it will simulate a "real" submit using the submit button)




回答3:


Not sure why you would want to do this, but I've tested it here with the following and it worked.

<form id="frm" action="#">
 <input type="submit" id="btnSubmit" />
  ...
  ...
</form>

Call this -> jQuery("#btnSubmit").trigger("click");




回答4:


Another alternative, tested in Chrome, Firefox, IE6, IE8:

window.location = $('a').trigger('click').href('attr');

I ended up using this because we have default jquery link handling on click events, but we also wanted to trigger an actual link visit (the link could be either a hash or a cross-domain link).



来源:https://stackoverflow.com/questions/940429/jquery-triggering-a-click

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!