JS事件委托学习
JS 事件委托就是利用冒泡原理,把事件加到父级上触发,执行效果。
<li>111111</li>
<li>22222</li>
<li>333333</li>
<li>444444</li>
</ul>
var oUl = document.getElementById("ul");
var oLi = oUl.getElementsByTagName("li")
for(var i = 0; i <oLi.length; i++){
oLi[i].onclick = function(){
alert(123)
}
}
}
alert(1123)
}
var oUl = document.getElementById("ul");
var oLi = oUl.getElementsByTagName("li")
for(var i = 0; i <oLi.length; i++){
oLi[i].onmouseover = function(){
this.style.background = "red"
}
oLi[i].onmouseout = function(){
this.style.background = ""
}
}
}
var oUl = document.getElementById("ul");
var oLi = oUl.getElementsByTagName("li")
oUl.onmouseover = function(ev){
var ev = ev || window.event; //事件
var target = ev.targe || ev.srcElement; //事件源,不管在哪个事件中,只要你操作的那个元素就是事件源
if(ev.target.nodeName.toLocaleLowerCase()=="li"){ // 事件在LI 上面才执行增加背景颜色
ev.target.style.background = "red"
}
}
oUl.onmouseout = function(ev){
var ev = ev || window.event;
var target = ev.targe || ev.srcElement;
ev.target.style.background = ""
}
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
window.onload = function(){
var oUl = document.getElementById("ul");
var oLi = oUl.getElementsByTagName("li")
var obtn = document.getElementById("input");
var iNow =4;
oUl.onmouseover = function(ev){
var ev = ev || window.event; //事件源,不管在哪个事件中,只要你操作的那个元素就是事件源
var target = ev.targe || ev.srcElement;
if(ev.target.nodeName.toLocaleLowerCase()=="li"){
ev.target.style.background = "red"
}
}
oUl.onmouseout = function(ev){
var ev = ev || window.event;
var target = ev.targe || ev.srcElement;
ev.target.style.background = ""
}
obtn.onclick=function(){
iNow++;
var oLi = document.createElement("li");
oLi.innerHTML = iNow * 11111;
oUl.appendChild(oLi)
}
}
</script>
</head>
<body>
<input type = "button" value= "增加" id = "input" />
<ul id="ul">
<li>111111</li>
<li>22222</li>
<li>333333</li>
<li>444444</li>
</ul>
</body>
</html>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。