猿问

关于JavaScript中“this”中的问题

  1. .为什么将以下代码中this,用sui[a]替换时,运行不出效果;

  2. .代码如下

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <style>

        .car{

            background: #1dacbe;

        }

    </style>

</head>

<body>

<button>按钮</button>

<button>按钮</button>

<button>按钮</button>

<button>按钮</button>

<button>按钮</button>

</body>

</html>

<script>

var sui=document.getElementsByTagName("button");

for(var a=0;a<sui.length;a++){

    sui[a].onclick=function () {

        for(var b=0;b<sui.length;b++){

            sui[b].className=""

        }

        this.className="car"

    }

}

</script>

慕田峪4524236
浏览 447回答 1
1回答

慕侠2389804

写个详细一点的- -&nbsp; &nbsp; for (var a = 0; a < sui.length; a++) {&nbsp; &nbsp; &nbsp; &nbsp; sui[a].index = a; //将当前循环的a值保存为当前按钮的index&nbsp; &nbsp; &nbsp; &nbsp; sui[a].onclick = function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (var b = 0; b < sui.length; b++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sui[b].className = '';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cosole.log(a);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sui[this.index].className = 'car';&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; }console.log(a);你就会发现,a返回的都是最后循环结束的值,你这里就是5,然后你只有5个按钮,就是01234...所以代码无效。sui[a].index = a可将每个循环的a的值存储到index,然后使用this.index调用,所以应该是sui[this.index]或者你把最外层的for的var改为let也行,这个写tab选项卡、轮播的控件的时候你都会用得到。最后你的问题,this是什么?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(sui[this.index]&nbsp;===&nbsp;this)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log('true'); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答