1

我写了这段代码来创建带有div标签的菜单

HTML:

<div id="firstMenuList">
            <div id="firstMenu">choose▼&lt;/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>

此代码创建菜单,但是当我单击菜单项时,代码会中断。错误是“父母为空” -

4

2 回答 2

1

要将 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/

于 2013-10-30T22:23:48.380 回答
0

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

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();
于 2013-10-30T22:27:18.187 回答