gpt4 book ai didi

javascript - 有没有一种简单的方法可以在 JQuery 中的两个节点集之间执行减法?

转载 作者:行者123 更新时间:2023-11-28 18:19:55 25 4
gpt4 key购买 nike

请注意:这个问题与我在这里找到的许多其他问题非常相似,但它不重复,所以请仔细阅读:

本质上,我想通过(比如说)类名从集合中排除节点及其所有后代。

我制作的扩展(检查代码片段)在给定的示例中工作得非常完美,但是我愿意找到更简单/更优雅的方法来实现它(如果它当前存在于 jquery 中)。

我正在寻找一种通用执行方式$(this).find('<some_selector>').exclude_found_nodes_that_have_the_following_between_aforementioned_this_and_itself('<exclusion_selector>') , 然而类似 $(this).find('<exclusion_selector>:ignore_branch_if_this_node_met() <some_selector>')也能完成这项工作。

ID 实际上并不存在于代码中,添加它们纯粹是为了演示目的(“起始节点”由用户选择)。

$.fn.find_exclude = function(original_selector,exclude_selector) {
var counter=$(this).parents(exclude_selector).length;
if ($(this).is(exclude_selector)){
counter++;
}
var tmp=$(this).find(original_selector);
return tmp.filter(function(){
if($(this).is(exclude_selector) || $(this).parents(exclude_selector).length>counter){
return false;
}
return true
});
};

$(function(){
var all_b_in_main_not_in_groups=$("#main").find_exclude('b','.group');
var all_b_in_inner_not_in_groups=$("#inner").find_exclude('b','.group');

all_b_in_main_not_in_groups.each(function(){
$(this).css('color','red');
});
all_b_in_inner_not_in_groups.each(function(){
$(this).css('opacity','0.5');
});



})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<span id="main">
<b>I should be red</b>
<div class="group" id="inner">
<span>
<b>I should be opaque but not red</b>
</span>
</div>
<div>
<b>I should be red</b>
<div class="group">
<b>Don't touch me, please.</b>
<div>
<b>Don't touch me, please.</b>
<p>
<b>Don't touch me, please.</b>
</p>
</div>
</div>
</div>
</span>

警告:在建议仅使用 :not 之前或.not() ,甚至使用 .clone() ,请再次重读问题和给定的示例,并检查您的解决方案是否确实有效 - 建议的解决方案应适用于 #main#inner作为起始节点(实际上不知道起始节点选择器 - 它们在 $(this) 事件监听器中被称为 click)

最佳答案

function customFind (findWhere, findWhat, ignoreWhat){
var totalIgnore = $(findWhere).find(ignoreWhat + ' ' + findWhat);
return $(findWhere).find(findWhat).not(totalIgnore);
}

用途:

var zzz= customFind(this,"b",".group");
zzz.css('text-decoration','underline');

关于javascript - 有没有一种简单的方法可以在 JQuery 中的两个节点集之间执行减法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40068983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com