[英]Select all elements inside a div but not a particular one
如何选择.content
所有元素,而不是.bts
? 这是我的代码。 我正在使用not()
函数来排除.bts
但它不起作用。 应该做什么?
$('.content').not('.bts').click(function() { alert("hit"); });
.content { height: 100%; width: 100%; } p {} .bts { background: blue; height: 100px; width: 100px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="content"> <p>test</p> <div class="bts">bts</div> </div>
你可以使用$('.content *:not(.bts)')
.content *
表示它将接受.content
上的所有元素, not(.bts)
添加not(.bts)
从规则中删除bts
class
所有元素。
演示
$('.content *:not(.bts)').click(function() { console.log("hit"); });
.content { height: 100%; width: 100%; } p {} .bts { background: blue; height: 100px; width: 100px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="content"> <p>test</p> <div class="bts">bts</div> </div>
的.content
是不是.bts
,所以.not
什么都不会做-相反,另一种选择传递到单击处理程序,以避免触发处理程序时.bts
点:
$('.content').on('click', ':not(.bts)', () => { console.log("hit"); });
.content { height: 100%; width: 100%; } p {} .bts { background: blue; height: 100px; width: 100px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="content"> <p>test</p> <div class="bts">bts</div> </div>
这就是你在Vanilla JS中实现它的方法
let elements = document.querySelectorAll(".content >:not(.bts)"); elements.forEach(ele => { ele.addEventListener("click", function() { alert("hit") }) })
.content { height: 100%; width: 100%; } p {} .bts { background: blue; height: 100px; width: 100px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="content"> <p>test</p> <div class="bts">bts</div> </div>
由于这个答案还没有发布,并且是根据他的代码解决OP问题的最简单的方法,我会这样做:你只是忘了选择.content
孩子,你可以用你的.children()
函数做到这一点。 .content
选择器如下:
$('.content').children().not('.bts').click(function() { alert("hit"); });
.content { height: 100%; width: 100%; } p {} .bts { background: blue; height: 100px; width: 100px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="content"> <p>test</p> <div class="bts">bts</div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.