开发者

JavaScript: Get clicked element

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:al开发者_高级运维ert(getClickedElement())" id="test">click me!!!</a>
</body>
</html>

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

Thanks.


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).

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.

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

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

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

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


the following statckoverflow question gives a way to detect clicked element here

$(document).click(function(event) {
    var text = $(event.target).text();
});


<a href="javascript:alert(getClickedElement('test'))" id="test">click me!!!</a>

<script>
function getClickedElement (id) {
    return document.getElementById(id);
}
</script>

or, if you can't predict the ID, you can use Javascript to attach events after page is loaded. Look at jQuery. Use something like $('a').click(function() {return this.id; });


To detect clicks on any element on the whole page, you can set the "click" event of the document, and that should activate no matter which element you click.

document.addEventListener("click", function(e) {
  console.log("You clicked this element:", e.target);
}); 

For right-clicking, the event is "contextmenu".

Even if the target element calls e.preventDefault(), this still detects the click. The only exception is if the the target or one of its parent calls e.stopPropagation().


you can pass this as a parameter and you can then know what is the element you are looking for. for example:

<html>
<head>
  <script>
    function getClickedElement ($this) {

    }
  </script>
</head>enter code here
<body>
  <a href="javascript:alert(getClickedElement(this))" id="test">click me!!!</a>
</body>
</html>

hope it will help you, it helped me :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜