简体   繁体   中英

Javascript click event on anchor not working

I was trying to call the click event when hitting spacebar on keyboard on an anchor like so.

$("a").on("keypress", function (e) { 
    if (e.which === 32) {
        $(this).click();
        e.preventDefault();
    }
}

This does not work however. I finally figured out a fix but I don't understand why it works. The simple fix was changing $(this).click() to $(this)[0].click()

What is the [0] doing and how is it making the click event work on the anchor?

Note: I also tried $(this).trigger("click") with no luck either.

See Roman Starkov's answer in the following link: Jquery how to trigger click event on href element

The native DOM method does the right thing:

 $('.cssbuttongo')[0].click(); ^ Important! 

This works regardless of whether the href is a URL, a fragment (eg #blah) or even a javascript:.

Note that this calls the DOM click method instead of the jQuery click method (which is very incomplete and completely ignores href).

So basically when you use the indexer you'll access the DOM's native click method instead of the jQuery implementation which does not work for links.

I wanted to mark this topic as duplicated but first I linked a wrong topic so I retracted the flag and now I cannot mark it again. So if someone has the power feel free to mark it as the duplicate of the linked topic. And if this answer helped upvote Roman Starkov's original answer in the link, he deserves it.

I didn't understanda exactly the scenario but that works for me, please try this:

 $('a').click(function() {
    alert('click...!');
  });

  //press enter on text area..

  $('a').keypress(function(e) {
    var key = e.which;
    console.log('checking press key: ' + key)
    if (key == 32) // the enter key code
    {
      $('a').click();

    }
  });

Feel free to rearrange...hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM