Home > Web Front-end > JS Tutorial > Implementation method of binding click event to each li node in JavaScript

Implementation method of binding click event to each li node in JavaScript

高洛峰
Release: 2016-12-03 09:30:26
Original
2614 people have browsed it

Click event

<body>
<h2>javascript 事件</h2>
<ul>
<li>aaaa</li>
<li>aaaa111</li>
<li>aaaa222</li>
<li>aaaa3333</li>
<li>aaaa444</li> 
</ul>
<script type="text/javascript">
//获取所有li的节点
var list = document.getElementsByTagName("li");
//给每个li绑定事件
for(var i = 0;i<list.length;i++){
list[i].onclick = function(){
//弹出对应的li节点里面的内容
alert(this.innerHTML);
//将节点的颜色变成红色
this.style.color = "red";
}
}
</script>
</body>
Copy after login

Double-click event

<body>
<h2>javascript 事件</h2>
<ul>
<li>aaaa</li>
<li>aaaa111</li>
<li>aaaa222</li>
<li>aaaa3333</li>
<li>aaaa444</li> 
</ul>
<script type="text/javascript">
//获取所有li的节点
var list = document.getElementsByTagName("li");
//给每个li绑定事件
for(var i = 0;i<list.length;i++){
list[i].ondblclick = function(){
//弹出对应的li节点里面的内容
alert(this.innerHTML);
this.style.color = "red";
}
}
</script>
</body>
Copy after login

PS: Let’s take a look at the js loop to bind click events with different parameters to li

<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<script type="text/javascript">
var li=document.getElementsByTagName_r("li");
for(var i=0;i<li.length;i++){
(function(x){
li[x].onclick=function(){alert(x);}
})(i);
}
</script>
Copy after login

The value that pops up for each li is different

The above is a small The JavaScript I introduced to you binds click events to each li node. I hope it will be helpful to everyone


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template