jquery click doesn't work on hyperlink

六眼飞鱼酱① 提交于 2019-11-26 16:35:22

问题


I have a simple link click simulation that I want to do using jQuery. From what I read, this should work, but the code below doesn't work. Nothing happens if I do the same thing as a part of some other event or something either. Thoughts?

<script type="text/javascript">
  $(function() {
    $("#lnk_0").click();
  });
</script>

<a id="lnk_0" href="http://mydomain.com/mypage.html">link</a>

回答1:


See click():

Triggers the click event of each matched element.

Causes all of the functions that have been bound to that click event to be executed.

The important thing to note is that it does not duplicate clicking the link. It only triggers associated events. If you want to change location:

var link = $("#link_0");
link.click();
window.location.href = link.attr("href");

but even that is only an approximation as it doesn't cater for handlers stopping event propagation.




回答2:


Calling jQuery's click method will invoke any click handlers that you've added, but will not click the link.

You need to write:

window.location = $("#lnk_0").attr('href');

(This assumes that there aren't any click event handlers)


EDIT: In response to your comment, you can call the IE-only DOM click method, like this:

if ($("#lnk_0")[0].click)
    $("#lnk_0")[0].click();
else
    window.location = $("#lnk_0").attr('href');



回答3:


To allow the hyperlink functionality (hover, hand cursor, etc) when overriding with jQuery you can do the following:

<script>
    $(function() {
        $( "#dialog-modal" ).dialog({
            autoOpen: false,
            height: 320,
            modal: true
        });

        $( "#open-modal" ).click(function() {
            $( "#dialog-modal" ).dialog( "open" );
        });         
</script>
<a href="javascript:return true" id="open-modal">Open Modal</a>

<div id="dialog-modal" title="Hello World">
Hello
</div>



回答4:


Doing this works:

$('#lnk_0')[0].click();



回答5:


I am not sure it solves your precise problem, but here is a snippet of code I use to simulate a user click:

var target = "...";

var e = jQuery.Event("click");

target.trigger(e);

if (!e.isDefaultPrevented() && target.attr("href"))
    window.location.href = target.attr('href');


来源:https://stackoverflow.com/questions/2053598/jquery-click-doesnt-work-on-hyperlink

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