尝试将addEventListener添加到循环数组中

时间:2018-02-25 23:04:04

标签: arrays events listen

我很确定我将事件处理程序部分编码错误。当阵列通过并循环时,它会在页面上产生一个列表。我只需要用事件监听器点击这个列表,然后根据if语句进行一系列重新定位以进行比较......想法?

window.onload = eventMonitor;



    function eventMonitor(){
    document.getElementById("names").addEventListener('click', reRoute, false);
    document.getElementById("hiddenText").addEventListener('mouseover', treasureRoute, false);


    function createName(){

        var streetNames = ["Carmen", "Napoli", "Oscar", "Haven", "Tampa"];
             //this top partscript creates a for loop that will take each array [item] and simply right it to the screen. 
                 for (i=0; i<streetNames.length; i++){

                var mName = "Martin";
                var node = document.createElement("li");
                var textNode = document.createTextNode(mName + " " + (streetNames[i])); 
                node.appendChild(textNode);
                document.getElementById("names").appendChild(node);
            }
        }
        function reRoute(){
                if(names === 'Martin Carmen'){
                    routeWindow = window.open("https://en.wikipedia.org/wiki/MSC_Carmen");
                }
                else if(names === 'Martin Napoli'){
                    routeWindow = window.open("https://en.wikipedia.org/wiki/MSC_Napoli")
                }
                else if(names === 'Martin Oscar'){
                    routeWindow = window.open("https://en.wikipedia.org/wiki/MSC_Oscar")
                }
                else if(names === 'Martin Haven'){
                    routeWindow = window.open("https://en.wikipedia.org/wiki/MT_Haven")
                }
                else if(names === 'Martin Tampa'){
                    routeWindow = window.open("https://en.wikipedia.org/wiki/MV_Tampa")
                }
        }
        function treasureRoute(){
                shipWindow = window.open("file:///Users/User/something.html");
         }
        }

1 个答案:

答案 0 :(得分:0)

您想要做的不需要JavaScript。 JavaScript虽然在许多情况下很有用,但在您注意到时很容易出错。 anchor标记用于在页面之间导航,这就是将<li><a href="Url">Text</a></li>元素注入DOM的原因。

如果你想在像你这样的情况下使用JavaScript,你可以编写你的事件处理程序以符合addEventListener API:

const names = document.getElementById('names');
names.addEventListnener('click', event => {
   const { target } = event;
   console.log(`${target.tagName} was clicked!`);
});