更改节点内容 + JavaScript 失败

Failure in changing node content + JavaScript

本文关键字:JavaScript 失败 节点      更新时间:2023-09-26

我为带有div标签的创建菜单编写了此代码

.HTML:

<div id="firstMenuList">
            <div id="firstMenu">choose▼</div> 
                <div id="menulist" class="menulist"></div>    
</div>

JavaScript:

<script>
function ccc() {
 
 var id="firstMenu";
 var ar=new Array("hi","there","hello","world");
 var node=document.createElement("div");
 var parent=document.getElementById("menulist");
 
 var nodeData="";
 for (var i=0;i<ar.length;i++)
 {
    var node=document.createElement("div");
    node.setAttribute("id",id+""+i);
    node.setAttribute("class","menulist");
    
    node.setAttribute("onclick","select("+id+""+i+")");
    node.style.top=((i+1)*100)+3+"%";
    node.innerHTML=ar[i];
    parent.appendChild(node);
    
 }
}
function select(id)
{   
 var p=document.getElementById(id);<-this doesn't work on elements that created dynamically
 p.style.backgroundColor="red";
 var t = p.innerHTML;
}
</script>

此代码创建菜单,但是当我单击菜单项时,代码中断。错误是:

"父级为空"

要将 id

传递给函数,您需要确保在 id 两边加上引号:

node.setAttribute("onclick","select('"+id+i+"')");
// note the single quotes ----------^--------^

演示:http://jsfiddle.net/QK5Wh/1/

但是,当

您可以将元素本身的直接引用传递给元素时,您不需要使用 id 来获取元素:

node.setAttribute("onclick","select(this)");

然后:

function select(p) {   
    p.style.backgroundColor="red";
    var t = p.innerHTML;
}

演示:http://jsfiddle.net/QK5Wh/

我建议避免内联事件绑定。这是一个工作示例:

http://jsfiddle.net/H4S2f/1/

function ccc() {
 var id="firstMenu";
 var cls="firstMenuList";
 var ar=new Array("hi","there","hello","world");
 var node=document.createElement("div");
 var parent=document.getElementById("menulist");
 var nodeData="";
 for (var i=0;i<ar.length;i++)
 {
    var node=document.createElement("div");
    node.setAttribute("id",id+""+i);
    node.setAttribute("class","menulist");
     (function(i) {
         node.addEventListener("click", function() {
             select(id+""+i)
         });
     })(i);
    node.style.top=((i+1)*100)+3+"%";
    node.innerHTML=ar[i];
    parent.appendChild(node);
 }
}
function select(id)
{   
 var p=document.getElementById(id);
 p.style.backgroundColor="red";
 var t = p.innerHTML;
}
ccc();