所以问题是我知道如何在 jQuery 中做到这一点,而且我知道 jQuery 是开放平台,所以我可以找到siblings() 实际做什么。 但我想用纯 js 或 Angular 来做,但没有指令。 纯 JS 的首选解决方案。 因此,当单击 div 时 addClass,但 sibling 会删除相同的类。
提前致谢。
这里是html
<div class="container">
<div class="row">
<div id="1">
<h1>asfsaff</h1>
</div>
<div id="2">
<h1>asfsaff</h1>
</div>
<div id="3">
<h1>asfsaff</h1>
</div>
<div id="4">
<h1>asfsaff</h1>
</div>
<div id="5">
<h1>asfsaff</h1>
</div>
<div id="6">
<h1>asfsaff</h1>
</div>
</div>
</div>
这是我的js
$scope.addParent = function(e) {
var men = event.target.getAttribute('data');
console.log(men);
var divSlide = document.querySelectorAll('div');
divSlide.forEach(function(getId){
var divId = getId.getAttribute('id');
if(men === divId) {
getId.className = "fsafsa";
}
});
}
最佳答案
以下是它的应用方式。找到您想要的节点,然后调用 getSiblings 并检索同级节点的集合,然后迭代它们并对它们执行您想要的任何操作:
var mySel = document.getElementById("2");
var myOthers = getSiblings(mySel);
// First, let's set the style of our selection
mySel.className = "selected"
// Next, let's de-toggle any others
for (var i=0; i<myOthers.length; i++){
myOthers[i].className = "not-selected";
}
// utility functions
function getChildren(n, skipMe){
var r = [];
for ( ; n; n = n.nextSibling )
if ( n.nodeType == 1 && n != skipMe)
r.push( n );
return r;
};
function getSiblings(n) {
return getChildren(n.parentNode.firstChild, n);
}
.row div {
padding: 5px;
}
.selected {
border: 1px dotted blue;
}
.not-selected {
border: 1px solid red;
}
<div class="container">
<div class="row">
<div id="1">
<h1>asfsaff</h1>
</div>
<div id="2">
<h1>asfsaff</h1>
</div>
<div id="3">
<h1>asfsaff</h1>
</div>
<div id="4">
<h1>asfsaff</h1>
</div>
<div id="5">
<h1>asfsaff</h1>
</div>
<div id="6">
<h1>asfsaff</h1>
</div>
</div>
</div>
查看了我在评论中提到的示例,这是相关的代码片段。一个非常优雅的纯 JavaScript 解决方案:
function getChildren(n, skipMe){
var r = [];
for ( ; n; n = n.nextSibling )
if ( n.nodeType == 1 && n != skipMe)
r.push( n );
return r;
};
function getSiblings(n) {
return getChildren(n.parentNode.firstChild, n);
}
因此 getSiblings 调用 getChildren 作为当前节点的父节点,然后简单地从返回的列表中删除当前节点。我喜欢它!
关于javascript - 获取点击元素的同级元素并removeClass纯javascript或没有指令的 Angular js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41882775/