js 迴圈新增點選事件
直接程式碼:
<!DOCTYPE html>
<html>
<!--方法比較簡單,就是使用for(var i = 0; i < li.length; i++) {
(function(x) {
li[x].onclick = function() { alert(x); }
})(i);
}
地址:
http://blog.sina.com.cn/s/blog_6bcf420101013f7o.html
具體就是解決傳送引數時候的解決問題
-->
<head>
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
li {
list-style: none;
float: left;
margin: 0 auto;
width: 24.5%;
height: 100%;
text-align: center;
line-height: 90px;
border-bottom: 1px solid #008000;
border-left: 1px;
border-right: 1px;
border-top: 5px;
}
li:hover {
border-bottom: 0px;
border-left: 1px solid #008000;
border-right: 1px solid #008000;
border-top: 5px solid #008000;
}
.mydiv {
display: none;
}
</style>
<script type="text/javascript">
window.onload = function() {
var mydiv = document.querySelectorAll(".mydiv");
var li = document.querySelectorAll("li");
for(var i = 0; i < li.length; i++) {
(function(x) {
li[x].onclick = function() {
for(var j = 0; j < li.length; j++) {
mydiv[j].style.display = "none";
}
mydiv[x].style.display = "block";
}
})(i);
}
}
</script>
</script>
</head>
<body>
<div style="position: relative; width: 100%; height: 500px; overflow: hidden;">
<div style="position: absolute; left: 0; top: 0; height: 100px; width: 100%; overflow: hidden;">
<ul>
<li>測試1</li>
<li>測試2</li>
<li>測試3</li>
<li>測試4</li>
</ul>
</div>
<div style="position: absolute; left: 0; top: 100px; height: 400px; width: 100%;">
<div class="mydiv" id="mydiv1" style="background: yellow; height: 100%; width: 100%;">這是佈局1</div>
<div class="mydiv" id="mydiv2" style="background: yellow; height: 100%; width: 100%;">這是佈局2</div>
<div class="mydiv" id="mydiv3" style="background: yellow; height: 100%; width: 100%;">這是佈局3</div>
<div class="mydiv" id="mydiv4" style="background: yellow; height: 100%; width: 100%;">這是佈局4</div>
</div>
</div>
</body>
</html>