简体   繁体   English

Apache Cordova addEventListener未添加

[英]Apache Cordova addEventListener not adding

I have looked at other questions and other sites online and have not been able to find a way to get addEventListener to work. 我在网上看过其他问题和其他网站,却找不到找到使addEventListener正常工作的方法。

I have a function called which adds buttons and adds event listeners for each button 我有一个名为的函数,该函数添加按钮并为每个按钮添加事件监听器

function displayData(){
    for(var key in localStorage){
        addButton(key);
    }
}

function addButton(name){
    var button = '<button id='+ name +'>'+name+'</button>';
    document.getElementById("container").innerHTML += button;
    // Line to add event listener
}

I have tested this many times and addButton always adds every button, but only one of the buttons works (the last one added). 我已经测试了很多次,并且addButton总是添加每个按钮,但是只有一个按钮起作用(最后一个按钮被添加)。 name is always different for each button. 每个按钮的名称总是不同的。 I have tried the following methods in Line to add event listener but none have worked 我在Line中尝试了以下方法来添加事件侦听器,但没有一个起作用

document.getElementById(name).addEventListener("click", foo);


//jQuery is included
$("#"+name).click(function(){
    foo();
});

and changing 和改变

'<button id='+ name +'>'+name+'</button>'

to

'<button onclick="foo();" id='+ name +'>'+name+'</button>'

When you do document.getElementById("container").innerHTML += "{your element}", you're effectively wiping out the existing inner elements and recreating them with one extra element. 当您执行document.getElementById(“ container”)。innerHTML + =“ {your element}”“时,您实际上是在清除现有的内部元素,并使用一个额外的元素重新创建它们。 This means your previous event listeners won't be there. 这意味着您以前的事件侦听器将不会在那里。 One way you can work around this is creating all your buttons first, then add your event listeners later. 解决此问题的一种方法是先创建所有按钮,然后再添加事件侦听器。 Or you could use appendChild to avoid recreating all the elements. 或者您可以使用appendChild避免重新创建所有元素。 Or better yet, use a framework like angular, react, or vue.js which will deal with this stuff for you so you don't go through the hassle of interacting with the DOM directly. 或者更好的是,使用诸如angular,react或vue.js之类的框架来为您处理这些事情,这样您就不必再经历直接与DOM交互的麻烦了。

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

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