本文介绍了JavaScript:获取点击元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在函数getClickedElement中获得clicked元素。我该怎么做?

I need to get clicked element in function getClickedElement. How can I do this?

<html>
<head>
  <script>
    function getClickedElement () {
    }
  </script>
</head>
<body>
  <a href="javascript:alert(getClickedElement())" id="test">click me!!!</a>
</body>
</html>

我只能设置href属性。
我无法设置onclick事件,因为这些元素是由第三方库生成的。

I can set only href attribute.I can not set onclick event because this elements is generated by third party lib.

谢谢。

推荐答案

您无法在 javascript:网址中获取点击的元素。该事件已经完成,因此没有 event.target (或IE的 window.event.srcElement ),以及 javascript:未使用集调用链接(因此您获得窗口)。

You can't get the clicked element in a javascript: URL. The event has already finished, so there's no event.target (or window.event.srcElement for IE), and javascript: links are not invoked with this set (so you get window).

当然,如果您知道,相关链接是 id =test你可以做 document.getElementById('test'),但我怀疑这是你想要做的事情。

Of course if you know the link in question is id="test" you can do document.getElementById('test'), but I suspect that's rather missing the point of what you want to do.

修复或删除lib。 javascript:网址是完全恐怖的,应该永远不会

Fix or drop the lib. javascript: URLs are utter horrors that should never be used.

你能添加吗?一个< script> 页面的其他地方?如果是这样,您可以在元素上注入单击事件处理程序,而无需任何额外的标记。例如:

Can you add a <script> elsewhere in the page? If so you can inject a click event handler onto the element(s) without needing any extra markup. eg.:

for (var i= document.links.length; i-->0;)
    if (document.links[i] is one of the links you want to target)
        document.links[i].onclick= someHandlerFunction;

function someHandlerFunction() {
    alert(this);
    return false;
}

确实,从JS分配(带 on .. 。或通过 addEventListener attachEvent IE的后备)是最佳实践方式无论如何都要添加事件处理程序。

Indeed, assigning from JS (with on... or via addEventListener with attachEvent fallback for IE) is the best-practice way of adding event handlers anyway.

这篇关于JavaScript:获取点击元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:56