在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ 以下代碼實(shí)現(xiàn)選項(xiàng)卡的功能,其中a [ i ].index=i;和p[this.i

以下代碼實(shí)現(xiàn)選項(xiàng)卡的功能,其中a [ i ].index=i;和p[this.index]不明白??

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
    <style>
        a{
            text-decoration: none;
            display: inline-block;
            background: #000;
            color: #fff;
            text-align: center;
            width: 100px;
            height:40px;
            line-height: 40px;
            font-size: 25px;
        }
        p{
            border:4px solid #000;
            display: none;
            height: 300px;
        }
    </style>
</head>
<body>
<a style="background: red;" href="#">第一個</a>
<a href="#">第二個</a>
<a href="#">第三個</a>
<p style="display: block">第一個的內(nèi)容</p>
<p>第二個的內(nèi)容</p>
<p>第三個的內(nèi)容</p>
<script>
    var a = document.querySelectorAll('a');
    var p = document.querySelectorAll('p');
    for(var i=0;i<a.length;i++){
        a[i].index = i;
        a[i].onclick = function () {
            for(var j=0;j<a.length;j++){
                a[j].style.background = '#000';
                p[j].style.display = 'none';
            }
            this.style.background = 'red';
            p[this.index].style.display = 'block';
        }
    }


</script>
</body>
</html>

其中js代碼中 a[i].index = i;p[this.index].style.display = 'block';不明白??
為什么不能直接使用p[i].style.display?
這行a[i].index = i;代碼什么意思

回答
編輯回答
裸橙

因?yàn)?code>click執(zhí)行的函數(shù)是相當(dāng)于是異步執(zhí)行,而i始終保持的是全局引用,當(dāng)你觸發(fā)click事件時,i實(shí)際上已經(jīng)為a.length了.所以你需要用a[i].index = i來保存每個dom節(jié)點(diǎn)的索引值。當(dāng)然你也可以用閉包來實(shí)現(xiàn),代碼如下:

    var a = document.querySelectorAll('a');
    var p = document.querySelectorAll('p');
    for(var i=0;i<a.length;i++){
         (function(i) {
             a[i].onclick = function () {
                for(var j=0;j<a.length;j++){
                    a[j].style.background = '#000';
                    p[j].style.display = 'none';
                }
                this.style.background = 'red';
                p[i].style.display = 'block';
            }
         
         })(i)
        
    }
2018年2月14日 03:54
編輯回答
夢若殤

執(zhí)行完之后,你的i一直為a.length的值

2018年5月16日 20:27
編輯回答
孤巷

這個是對多個a標(biāo)簽賦予動作,因?yàn)榍懊娌樵兊降腶標(biāo)簽有多個,所以a[i]就是依次取不同的a標(biāo)簽元素進(jìn)行處理。
p標(biāo)簽的也是類似的。
這個應(yīng)該是一個切換選項(xiàng)卡效果,它先把所有的p標(biāo)簽都隱藏,然后選擇一個取消隱藏來顯示。p[this.index]這里因?yàn)槭侵敢粋€a的觸發(fā)函數(shù)中,所以會取到對應(yīng)a的index值。

2018年2月11日 03:10