jquery父级、子级的简写
我一直在影响与其他元素相关的元素,但我的方法有点业余jquery父级、子级的简写,jquery,parent,relative-path,children,Jquery,Parent,Relative Path,Children,我一直在影响与其他元素相关的元素,但我的方法有点业余 $(this).parent('div').parent('div').parent('div').children('a.postMore').css('display','block'); ie to // <div> <div> <div> <ul> matched item where script is called from </ul> </div> &l
$(this).parent('div').parent('div').parent('div').children('a.postMore').css('display','block');
ie to
// <div> <div> <div> <ul> matched item where script is called from </ul> </div> </div> <a class="postMore">LINK</a> </div>
$(this).parent('div').parent('div').parent('div').children('a.postMore').css('display','block');
看起来有点麻烦。有没有更好的方法来处理相关元素?有多种方法可以处理,因此您只需确定html结构中的模式,并使用最相关的方法即可
$(this).parent('div').parent('div').parent('div').children('a.postMore').css('display','block');
在您的示例中,这应该做您想要做的事情,并且它允许更大的灵活性
$(this).parent('div').parent('div').parent('div').children('a.postMore').css('display','block');
$(this).closest('div:has(a.postMore)').find('a.postMore');
演示
$(this).parent('div').parent('div').parent('div').children('a.postMore').css('display','block');
- 将上升到最高点 直到找到一个 匹配我们作为参数传递的选择器
- 我们的选择器是
,这意味着div:has(a.postMore)
包含与类div
的链接postMore
- 然后,我们使用链接来访问实际链接
.closest()
向上搜索DOM树。因此,如果您给包含a.postMore
的div指定了一个类,则可以使用$(this).closest('class')。children('a.postMore')
)。
文档您不必为container div指定一个类。这里有一个选择器用于此操作。很好,我不知道这一点。谢谢你和+1的回答。太棒了-谢谢加布!find有什么处理问题吗?@daniel,你是说效率问题吗?否,
.find()
是向下遍历DOM层次结构最常用的方法,如果指定的选择器允许,它将使用本机浏览器方法进行工作。
$(this).parent('div').parent('div').parent('div').children('a.postMore').css('display','block');