简体   繁体   English

锚点上的JavaScript单击事件不起作用

[英]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. 我试图在锚点上按下键盘上的空格键时调用click事件。

$("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() 简单的解决方法是将$(this).click()更改$(this)[0].click()

What is the [0] doing and how is it making the click event work on the anchor? [0]在做什么,它如何使click事件在锚点上起作用?

Note: I also tried $(this).trigger("click") with no luck either. 注意:我也尝试了$(this).trigger("click")没有运气。

See Roman Starkov's answer in the following link: Jquery how to trigger click event on href element 请参阅以下链接中的Roman Starkov的答案: jQuery如何触发href元素上的click事件

The native DOM method does the right thing: 本机DOM方法做正确的事情:

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

This works regardless of whether the href is a URL, a fragment (eg #blah) or even a javascript:. 无论href是URL,片段(例如#blah)还是javascript :,这都有效。

Note that this calls the DOM click method instead of the jQuery click method (which is very incomplete and completely ignores href). 请注意,这将调用DOM click方法而不是jQuery click方法(这是非常不完整的,并且完全忽略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. 因此,基本上,当您使用索引器时,您将访问DOM的本机click方法,而不是不适用于链接的jQuery实现。

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. 如果此答案有助于在链接中支持Roman Starkov的原始答案,那么他应得的。

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! 随意重新排列...希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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