English 中文(简体)
添加 生计活动在静态纽州进行,但不在动态生成的纽芬兰进行。
原标题:addEventListener works on static buttons, but not on dynamically generated buttons
  • 时间:2012-05-09 01:09:16
  •  标签:

我有一个纽芬兰语气球。

<button id= test >TEST BUTTON</button>

Then I have this function and listener in a separate js file.

function getAjax()
{
    chrome.tabs.executeScript(null, {code:"alert( works! )"});
}

document.addEventListener( DOMContentLoaded , function () {
    var buttons = document.querySelectorAll( button );
    for (var i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener( click , getAjax);
  }
});`

当我使用上述纽芬兰语时,这项职能便被称作。 现在,如果我能像现在这样动态地产生纽州:

var AJAXholder = document.getElementById("AJAXholder"); 
var button = document.createElement("button");
button.setAttribute("class", "app-buttons");                
button.setAttribute("id", ""+ objects[i].name +"");
button.setAttribute("name", ""+ objects[i].name +"");
    var buttonText = document.createTextNode(""+ objects[i].name +"");
    button.appendChild(buttonText);
AJAXholder.appendChild(button);

这些纽州是正确的,但无法发射这一功能。 我能做些什么来使其发挥作用?

EDIT:

I added a new event listener as I make a new button, like so:

var newlistener = document.getElementById(""+ objects[i].name +"").addEventListener( click , getAjax);

似乎工作。 如果我允许的话,我会想以更好的方式学习,或投票删除。

问题回答

Is your button-generating code contained in your DOMContentLoaded listener function? If not, my guess is that DOMContentLoaded is firing before the JS script runs to create the buttons, so querySelectorAll( button ) gets an empty list, since no buttons exist yet. Make sure your button-creation script runs chronologically after (or, better still, within) your DOMContentLoaded listener function.





相关问题
热门标签