我一直需要影响与其他元素相关的元素,但我的方法有点业余!
即到
// <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');
这看起来有点麻烦。有没有更好的方法来处理相对元素?
最佳答案
有多种方法可以traverse the DOM with jQuery ,因此您只需识别 html 结构中的模式,并使用最相关的方法。
在您的示例中,这应该可以满足您的要求,并且具有更大的灵 active 。
$(this).closest('div:has(a.postMore)').find('a.postMore');
演示 http://jsfiddle.net/gaby/j2Wgv/
<小时/>-
.closest()
将向上移动到 DOM 直到找到一个元素 与我们作为参数传递的选择器匹配。 - 我们的选择器是
div:has(a.postMore)
,这意味着div
包含类postMore
的链接 - 然后我们使用
.find()
到达实际链接。
关于jquery 父、子的简写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6095621/