简体   繁体   English

如何获取addEventListener参数

[英]How to get addEventListener arguments on <a href >

I have a PHP script that generates links - I want to use addEventListener to pick up arguments on these links but what ever I try seems to fail. 我有一个生成链接的PHP脚本 - 我想使用addEventListener来获取这些链接上的参数,但我尝试过的东西似乎都失败了。 It's very old code that used to work with onClick events but I'm updating the code and beleived that addEventListener is the way to go. 这是一个非常古老的代码,用于处理onClick事件,但我正在更新代码,并且相信addEventListener是要走的路。

I've taken my code back to basics to test the best code solution. 我已经将我的代码重新用于测试最佳代码解决方案的基础知识。

So I have links like so 所以我有这样的链接

    <a href="#" id="1" data-un-str="miguel" class="nameClick" >Alert Name1</a>
    </br>
    <a href="#" id="2" data-un-str="sarah" class="nameClick" >Alert Name 2</a>
    </br>

and a function 和一个功能

    function buildlink(e) 
    {
    var e = window.e || e;
    if (e.target.tagName !== 'A')
        return;
    alert(e.id);
    }

and event handler like this. 和事件处理程序这样。

window.onload=function(){
if (document.addEventListener)
    document.addEventListener('click', buildlink, false);

The event handler works, and picks up the clicks on the links. 事件处理程序工作,并获取链接上的点击。

I just don't understand how to pick up the arg data in id, but most of all I'd like to know how to pick up the args in data-un-str too. 我只是不明白如何在id中获取arg数据,但最重要的是我想知道如何在data-un-str中获取args Eg "miguel" or "sarah" 例如“米格尔”或“莎拉”

I presume it is possible as I've seen it done elsewhere, I just couldn't work out how it had been done. 我认为它是可能的,因为我已经看到它在其他地方完成,我只是无法弄清楚它是如何完成的。 I used to code JS a lot more about 10+ years ago, but I'm a bit lost now on DOM stuff and things seem to have changed alot. 我过去常常在大约10年前编写JS代码,但是现在我对DOM的东西有点迷失,而且事情似乎已经发生了很大变化。

For the code above when it tries to alert the id of the link clicked I just get 'undefined' in my alert. 对于上面的代码,当它试图提醒点击链接的id时,我只是在我的警报中得到'undefined'。

Any advice would be great. 任何建议都会很棒。 Thanks 谢谢

The event.target (where event is the first parameter passed to the handler) will refer to the clicked element, and you can get the data-un-str attribute by checking the target's .dataset.unStr property: event.target (其中event是传递给处理程序的第一个参数)将引用单击的元素,您可以通过检查目标的.dataset.unStr属性来获取data-un-str属性:

 function buildlink(event) { const { target } = event; if (target.tagName !== 'A') { return; } const { id, dataset } = target; const { unStr } = dataset; console.log(id, unStr); } window.onload = function() { if (document.addEventListener) document.addEventListener('click', buildlink, false); } 
 <a href="#" id="1" data-un-str="miguel" class="nameClick">Alert Name1</a> <br> <a href="#" id="2" data-un-str="sarah" class="nameClick">Alert Name 2</a> <br> 

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

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