给定一个具有多个级别后代的jquery对象,如何排除某些后代及其后代?假设在要排除的元素的顶部节点上有一个类(在这种情况下为div1
),并且您的jquery对象是下面的.foo
。
编辑:澄清:我想排除$('#button1').click(function() {
var selector = '#test ' + $('#input1').val();
var numberElements = $(selector).length;
$('#numberElements').text(numberElements);
var elementsAsCommaSeparatedList = _.pluck($(selector), 'id');
$('#elementList').text(elementsAsCommaSeparatedList.join(', '));
});
的所有后代,而不仅仅是直接的孩子。
#input1 {
width: 230px;
font-size: 16px;
font-weight: bold;
}
#numberElements,
#elementList {
color: green;
font-weight: bold;
font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="input1">Please supply a selector... $('<input id="input1" value="div:not(.foo, .foo *)"></label>')
<button id="button1">Apply Selector</button>
<div>(default value is from @DaniP's answer)</div>
<div id="result"><span>Number of elements selected: </span><span id="numberElements">0</span></div>
<div>
<span>Elements selected (by id):</span>
<span id="elementList"></span>
</div>
<div id="test">
<div id="div1">
<div id="div2">
<div id="div4">
<div id="div8"></div>
<div id="div9"></div>
</div>
<div id="div5" class="foo">
<div id="div10"></div>
<div id="div11"></div>
</div>
</div>
<div id="div3">
<div id="div6">
<div id="div12"></div>
<div id="div13"></div>
</div>
<div id="div7" class="foo">
<div id="div14"></div>
<div id="div15"></div>
</div>
</div>
</div>
</div>
build-essential
答案 0 :(得分:5)
使用Jquery,您可以在:not
选择器上使用多个参数,这样很容易排除.foo
和子元素:
$('div:not(.foo, .foo *)')
示例代码段
$('div:not(.foo, .foo *)').css('border-color','blue')
div {
padding-left:20px;
margin:5px;
border:thin red solid;
}
.foo {
background:rgba(0,0,0,.1)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
DIV1
<div>
DIV2
<div>
DIV4
<div>DIV8</div>
<div>DIV9</div>
</div>
<div class="foo">
DIV5
<div>DIV10</div>
<div>DIV11</div>
</div>
</div>
<div>
DIV3
<div>
DIV6
<div>DIV12</div>
<div>DIV13</div>
</div>
<div class="foo">
DIV7
<div>DIV14</div>
<div>DIV15</div>
</div>
</div>
</div>
但CSS不允许这样做,refer to this answer。
在CSS上,你需要定位所有不是.foo
的div,但是还要再次覆盖.foo
的子元素:
div:not(.foo) {
border-color:blue;
}
div.foo * {
border-color:red;
}
示例代码段
div {
padding-left:20px;
margin:5px;
border:thin red solid;
}
.foo {
background:rgba(0,0,0,.1)
}
div:not(.foo) {
border-color:blue;
}
div.foo * {
border-color:red;
}
<div>
DIV1
<div>
DIV2
<div>
DIV4
<div>DIV8</div>
<div>DIV9</div>
</div>
<div class="foo">
DIV5
<div>DIV10</div>
<div>DIV11</div>
</div>
</div>
<div>
DIV3
<div>
DIV6
<div>DIV12</div>
<div>DIV13</div>
</div>
<div class="foo">
DIV7
<div>DIV14</div>
<div>DIV15</div>
</div>
</div>
</div>
答案 1 :(得分:0)
也许使用:not selector?
像
这样的东西div:not(.foo)