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

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

高洛峰
高洛峰Original
2016-12-03 09:30:262593browse

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>

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>

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>

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


Statement:
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
Previous article:Vue.js(vue-router)Next article:Vue.js(vue-router)