如何为来自服务器的元素添加事件列表?
-
06-07-2019 - |
题
如何使用addEventListener(window.onload)添加click事件 当正在生成有问题的标签时 服务器(通过xmphttp请求,不能少)?
谢谢!
解决方案
在元素插入DOM后,你必须应用事件处理程序
其他提示
您可以尝试处理父元素的事件,这些元素可以作为DOM加载,然后获取与事件相关的元素。
<ul id="list">
<li id="first">The first</li>
<li id="second">The second</li>
<li id="third">The third</li>
</ul>
document.getElementById('list').onclick(function(e){
o = e.originalTarget;
// if you click on second li o will bi the same as document.getElementById('first')
// even if li with id "first" is inserted to DOM after creating this event handler to "list"
// so here you can perform actions with it
// hope it will help
});
谢谢大家。
我通过将以下代码添加到“成功时”来解决这个问题。 XMLHTTP请求的事件,该请求使用来自服务器的元素填充DOM。这对我有用。 乔希,你让我的头朝着正确的方向前进(尽管看到代码插图会很不错)所以我将你的回答标记为答案。
if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
var m_sel=document.getElementById("fcat");
if (m_sel) {
var maxi = m_sel.options.length;
for( var i = 0; i < maxi; i++ )
{
var option = m_sel.options[i];
option.addEventListener( "click", toggleElem, true );
}
}
}
不隶属于 StackOverflow