简体   繁体   English

JavaScript Click事件是通过Enter键触发的,而不是通过Mouse触发的

[英]JavaScript Click event fires via the Enter Key but not via the Mouse

Some code that looks like the following is firing the click event via the Enter key, but is not responding to the mouse click. 类似于以下代码的某些代码通过Enter键触发了click事件,但没有响应鼠标单击。

//a is an anchor element
a.addEventListener('click', function (e)
{
    //Do Stuff...
});

This page demonstrates the problem. 此页面演示了该问题。 The relevant bit of code is at line 176. This is in the middle of development and currently only (sort of) works in Chrome . 相关的代码位在第176行。这是在开发过程中,目前(仅)在Chrome中有效

Also, I just verified that it works if I use mousedown , so it's not just the case of an invisible element sitting in front of the anchor. 另外,我刚刚验证了如果使用mousedown可以正常工作,因此不只是锚点前面不可见元素的情况。

Any ideas? 有任何想法吗?

Edit: Now that you've shown us the actual code you're using, the problem is related to the fact that the autoSuggest() function has it's own click handler and in that click handler, it is clearing the container which removes all <a> elements in the container so your link object gets destroyed (probably before your click event gets to process). 编辑:现在,您已经向我们展示了正在使用的实际代码,该问题与以下事实有关: autoSuggest()函数具有其自己的单击处理程序,并且在该单击处理程序中,它正在清除容器,该容器将删除所有<a>容器中的元素,因此您的链接对象将被销毁(可能在click事件得到处理之前)。 So, you can get events that happen before the click (like mousedown), but after a click, the element is removed from the DOM. 因此,您可以获得在单击之前发生的事件(例如,鼠标按下),但是在单击之后,该元素将从DOM中删除。

If you tell us what you're trying to actually do when an auto-suggest item is clicked that is different than the default behavior of the autoSuggest() function and you point to any documentation for that function, then perhaps we could offer a better way to solve your issue. 如果您告诉我们单击自动建议项与autoSuggest()函数的默认行为不同时要尝试执行的操作,并且您指向该函数的任何文档,那么也许我们可以提供更好的选择解决您的问题的方法。


The link may be firing and taking you off to a new page (or reloading the current page), thus preventing you from seeing the click code run. 该链接可能会触发并带您进入新页面(或重新加载当前页面),从而使您无法查看点击代码的运行情况。 Usually when you process a click event on a link element, you need to prevent the default behavior: 通常,当您处理链接元素上的click事件时,您需要防止默认行为:

//a is an anchor element
a.addEventListener('click', function (e) {
    e.preventDefault();
    //Do Stuff...
});

Another possibility is that you are trying to install the event handler too soon either before the DOM has been loaded or before this particular link has been created and thus no actual click event handler is attached to the DOM object. 另一种可能性是,您试图在加载DOM之前或在创建此特定链接之前过早安装事件处理程序,因此没有实际的单击事件处理程序附加到DOM对象。 You can verify whether the event handler is even getting called by temporarily putting an alert("Click handler called"); 您可以通过暂时放置alert("Click handler called");来验证事件处理程序是否被调用alert("Click handler called"); in the event handler and see if that pops up or not. 在事件处理程序中查看是否弹出。

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

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