JavaScript----同步异步和排他思想

2018-11-10  本文已影响0人  AuglyXu

同步和异步

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>93-同步和异步</title>
</head>
<body>
<button>我是第1个按钮</button>
<button>我是第2个按钮</button>
<button>我是第3个按钮</button>
<button>我是第4个按钮</button>
<button>我是第5个按钮</button>
<script>
var btns = document.querySelectorAll("button");
for(var i = 0,len = btns.length;i<len;i++){
      btns[i].onclick = function(){
      console.log("我是第",i,"个按钮")
  }
}
//当按下按钮的时候永远输出我是第5个按钮
</script>

解决方案

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>93-同步和异步</title>
</head>
<body>
<button>我是第1个按钮</button>
<button>我是第2个按钮</button>
<button>我是第3个按钮</button>
<button>我是第4个按钮</button>
<button>我是第5个按钮</button>
<script>
var btns = document.querySelectorAll("button");
for(var i = 0,len = btns.length;i<len;i++){
     (function(index){
       btns[index].onclick = function(){
      console.log("我是第",index,"个按钮")
  }
})(i)
}
</script>
</body>
</html>
(function(index){
       btns[index].onclick = function(){
      console.log("我是第",index,"个按钮")
  }
})(i)

//等价于
function test(index){
       btns[index].onclick = function(){
      console.log("我是第",index,"个按钮")
  }
}
test(i)

排他思想

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>94-高级排它</title>
    <style>
        .selected{
            background: red;
        }
    </style>
</head>
<body>
<ul>
    <li class="selected">我是第1个li</li>
    <li>我是第2个li</li>
    <li>我是第3个li</li>
    <li>我是第4个li</li>
    <li>我是第5个li</li>
</ul>
<script>
var oLis = document.querySelectorAll("ul>li");
var currentIndex = 0;
for(var i = 0,len = oLis.length;i < len;i++){
  (function(index){
    oLis[index].onmouseenter = function(){
    this.className = ".select"
    oLis[currentIndex].className = ""
    currentIndex = index.
  })(i)
}
</script>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读