从Event Listener e.path Array中提取元素的id?

时间:2018-01-30 18:36:53

标签: javascript javascript-events addeventlistener

我正试图绕过赛事,我完全迷失了?我想使用e.path Array从事件监听器访问元素id?我想要的id总是在objTmp Array()的文章id =“someID”节点。

我也可以弄清楚为什么这只适用于Chrome所有其他浏览器都说objTmp未定义?

任何帮助将不胜感激......

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Working </title>

    <style type="text/css">
    </style>

    <script type="text/javascript">

        function init() {

            var eventTmp = document.querySelectorAll("ul li");
            for (var i = 0; i < eventTmp.length; i++) {
                eventTmp[i].addEventListener('click', function (e) {
                    var objTmp = e.path;
                    for (var i = 0; i < objTmp.length; i++) {
                        
                        if (objTmp[i].tagName === "ARTICLE") {
                            //This is where I get lost
                            //How do I get the id from this node??
                            var x = objTmp[i];
                            console.log(x);
                        }
                    }
                    e.stopPropagation();
                }, false);

            }
        }

    </script>
</head>
<body onload="init()">
    <main id="">
        <article id="id_Article0">
            <section>
                <h2>Header</h2>
                <div>
                    <ul>
                        <li>Link 1</li>
                        <li>Link 2</li>
                        <li>Link 3</li>
                    </ul>
                </div>
            </section>
        </article>
        <article id="id_Article1">
            <section>
                <h2>Header</h2>
                <div>
                    <p>
                        <h3>Some Text</h3>
                        <ul>
                            <li>Link 1</li>
                            <li>Link 2</li>
                            <li>Link 3</li>
                        </ul>
                    </p>
                </div>
            </section>
        </article>
    </main>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

我有更好的运气:

e.target.id

如果有多个目标,那么:

e.target[i].id

一个更大的问题我看到你的forter for循环和你的嵌套for循环都有相同的计数器变量i。 你想给内部for循环一个不同的计数器变量。

答案 1 :(得分:0)

这是一种在不使用event.path的情况下定位祖先ARTICLE节点的方法:

function init() {

    var eventTmp = document.querySelectorAll("ul li");
    for (var i = 0; i < eventTmp.length; i++) {
        eventTmp[i].addEventListener('click', function (e) {
          var articleNode = this;
          while (articleNode.nodeName != "ARTICLE" && articleNode.nodeName != "BODY") {
            articleNode = articleNode.parentNode;
          }
          if (articleNode.nodeName == "BODY") {
            // no article ancestor was found
          } else {
            // do something with articleNode
            console.log(articleNode.id);
          }

          e.stopPropagation();
        }, false);
    }
}