请看第33行,给新添加的li元素绑定删除事件,提示语法错误,为什么呢?谢谢
cn("deletes")[0].addEventListener("click",function(){$("outer_wrap").removeChild(this.parentNode)});
<body>
<button id="adds">添加</button>
<button id="delete">删除</button>
<ul id="outer_wrap">
<li>
<input type="text" value="标题1"><input type="text" value="链接">
<button>submit</button>
<button class="deletes">delete</button>
</li>
<li>
<input type="text" value="标题2"><input type="text" value="链接">
<button>submit</button>
<button class="deletes">delete</button>
</li>
</ul>
<script>
/*dom操作方法*/
function $(id){
return document.getElementById(id);
}
function cls(element){
return document.getElementsByTagName(element);
}
function cn(element){
return document.getElementsByClassName(element);
}
/*添加li元素*/
function add_li(){
var newli = document.createElement("li");
$("outer_wrap").insertBefore(newli,cls("li")[0]);
cls("li")[0].innerHTML="<li><input type='text' value='标题2'><input type='text' value='链接'><button>submit</button><button class='deletes'>delete</button></li> ";
/***这里********/
/***这里********/
/*给新添加的li元素绑定删除事件*/
cn("deletes")[0].addEventListener("click",function(){$("outer_wrap").removeChild(this.parentNode)});
/***这里********/
/***这里********/
}
/*移除li*/
function remove_li(){
$("outer_wrap").removeChild(this.parentNode)
}
/*给删除按钮绑定移除事件*/
function bind_del(){
for(i=0;i<2;i++)
{
cn("deletes")[i].addEventListener("click",remove_li);
}
}
bind_del();
/*绑定添加li事件*/
$("adds").addEventListener("click",add_li);
</script>
你这写的不对,ul里套了两层li,this.prarentNode是li 里的li,所以不对,把
cls("li")[0].innerHTML="<input type='text' value='标题2'><input type='text' value='链接'><button>submit</button><button class='deletes'>delete</button> ";
去掉,另外cn("deletes")[0].addEventListener()改为newli.addEventListener()。获取class是动态的