Why can't I click() links in jQuery?

馋奶兔 提交于 2019-12-01 09:18:49

domelement.click() isn't supported cross browser for redirecting. If you need to redirect to the location in a link you can use:

window.location = $('#link').prop('href');

jQuery.click() is meant to bind a click handler to an element. However it can be used to trigger a click() event bound using jQuery.

jQuery.trigger() will trigger a bound event handler, such as $(someElement).trigger("click");

If you wanted to trigger a link in jQuery may I suggest the following.

$(someelement).click(function () {
  window.location = $(link).attr("href");
});

Maybe this is what you are looking for? First, you need to attach a click event. then you can use trigger to fire it.

<html>
<head title="jQuery Test">
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.7.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#blah').click(function () {
                alert('clicked');
            });
            $('#blah').trigger('click');
        });
    </script>
</head>
<body>
    <a id="blah" href="#">BLAH</a>
</body>
</html>

For why this isn't work, in jsFiddle $('#link') doesn't select the anchor in html, and click() fails. Even the type selector $('a').href fails.

http://jsfiddle.net/yangchenyun/L9EUS/

The code works in normal browser. I have tested the code on stackoverflow.com with this code jQuery('a').eq(1).click() in chrome concole, it triggers the click() on the logo.

So in conclusion, click() links work in jQuery(). jsfiddle.net has interrupts the normal jQuery function.

I'm just guessing as to why the jQuery team chose to implement things this way, since I'm not on the jQuery team, but the navigation aspect of an anchor tag can be triggered by other UI behaviors than just clicking with the mouse. For example in plain old javascript, using the keyboard to activate an element doesn't trigger the onClick action, but it will trigger the navigation action of an anchor tag.

In other words, by clicking on a link you're just using one of several possible mechanisms for navigating to the referenced endpoint, but the navigation and the click aren't the same event, so jQuery chose to treat the click just that.

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