更改节点内容 + JavaScript 失败
Failure in changing node content + JavaScript
我为带有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();
相关文章:
- 缓存javascript失败,因为使用了外部javascript
- net::ERR_CONTENT_LENGTH_MISMATCH-加载javascript失败
- JavaScript 失败,出现权限被拒绝错误消息
- 更改节点内容 + JavaScript 失败
- 在 WatiN 中运行 JavaScript 失败
- 获取类中的类时,Javascript失败
- 将asp.net变量传递给javascript失败
- 重定向除Chrome外所有浏览器中的javascript失败
- EO.WEB动态生成的JavaScript失败,返回404
- phonegap中的javascript失败
- 当我加载prototype.js时,我的javascript失败了,如何修复它
- Javascript失败的xpath查询,如何避免它
- 动态加载javascript失败,但innerHTML失败
- JavaScript:失败的图像请求是否有error属性
- 在Google Chrome浏览器中查询Sharepoint Javascript失败- 404错误
- Redmine + Lighttpd:加载javascript失败(404)
- Foreach循环javascript失败
- Facebook SDK与Javascript失败,不知道为什么
- POST到GitHub v3 API使用ajax和JavaScript失败与HTTP 404
- JavaScript失败,原因尚不清楚