Skip to content Skip to sidebar Skip to footer

Why Can't I Click() Links In Jquery?

I came across a curiosity in jQuery: if I call .click() on a link the click event handlers are called, but the link isn't actually followed (as if it were clicked in the browser):

Solution 1:

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');

Solution 2:

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");
});

Solution 3:

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><headtitle="jQuery Test"><scripttype="text/javascript"src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.7.js"></script><scripttype="text/javascript">
        $(document).ready(function () {
            $('#blah').click(function () {
                alert('clicked');
            });
            $('#blah').trigger('click');
        });
    </script></head><body><aid="blah"href="#">BLAH</a></body></html>

Solution 4:

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.

Solution 5:

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.

Post a Comment for "Why Can't I Click() Links In Jquery?"