原生 JS如何实现类似Jquery的siblings功能?

如题:
比如我body里面有这么几个链接:

    <a href="javascript:;">连接一</a>

    <a href="javascript:;">连接二</a>

    <a href="javascript:;">连接三</a>

    <a href="javascript:;">连接四</a>

    <a href="javascript:;">连接五</a>

    <a href="javascript:;">连接六</a>

    <a href="javascript:;">连接七</a>

    <a href="javascript:;">连接八</a>

    <a href="javascript:;">连接九</a>

var link = document.getElementsByTagName("a");

for (var i = 0; i < link.length; i++) {

    link[i].addEventListener("click", function() {

        this.style.backgroundColor = "#000";

    })

}

现在能实现单击其中一个链接改变它的背景色,但是如何能实现JQ中很容易实现的功能,点击其中一个,其它的样式也同时变了(切换)。

有只小跳蛙
浏览 830回答 1
1回答

慕莱坞森

<style>body{&nbsp; background:#CCC;}a{&nbsp; display:inline-block;&nbsp; width:100px;&nbsp; padding:5px 10px;&nbsp; background:#666;&nbsp; text-align:center;&nbsp; color:#FFF;&nbsp; border:solid 3px #333;&nbsp; margin:1px;}a.active{&nbsp; background-color:#FF0;&nbsp; border-color:#C00;&nbsp; color:#C00;}</style><div id="parent">&nbsp; <a href="javascript:;">连接一</a>&nbsp; <a href="javascript:;">连接二</a>&nbsp; <a href="javascript:;">连接三</a>&nbsp; <a href="javascript:;">连接四</a>&nbsp; <a href="javascript:;">连接五</a>&nbsp; <a href="javascript:;">连接六</a>&nbsp; <a href="javascript:;">连接七</a>&nbsp; <a href="javascript:;">连接八</a>&nbsp; <a href="javascript:;">连接九</a></div><script>document.getElementById("parent").addEventListener("click", function(event){&nbsp; &nbsp; if( event.srcElement.tagName.toLowerCase() == "a" ){&nbsp; &nbsp; &nbsp; &nbsp; if( this.lastClick != event.target){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; event.target.className = "active";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if( !!this.lastClick){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.lastClick.className = "";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.lastClick = event.target;&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("重复点击不触发");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }});</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript