我使用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>
此代码创建菜单,但是当我点击菜单项时代码中断。 错误是“父级为空” -
答案 0 :(得分: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;
}
答案 1 :(得分:0)
我建议避免使用内联事件绑定。这是一个有效的例子:
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();