我需要爬上 DOM 树到节点的父节点、祖 parent 、曾祖 parent 等(没有任何兄弟节点)并设置一些属性。我认为在树上运行一个简单的递归就可以解决问题,但我就是无法让它发挥作用。我尝试了很多看起来合乎逻辑的不同事情,但 javascript 不与我合作。有人可以帮忙吗?
这是一个 JSFiddle,显示了我正在尝试执行的操作的非工作版本: http://jsfiddle.net/ry8ojoaj/
// This function should climb up the chain of parent 'group's (but not uncles or aunts)
// and set their 'group-things' to have a red background
var setParentChainText = function(node) {
if (!node) { return; }
node.css('background-color', 'red');
var parent = node.closest('.group').first()
if (node.hasClass('group-thing')) {
parent = node.parents('.group').first()
}
var parentThing = parent.find('.group-thing').first();
setParentChainText(parentThing);
}
$(function() {
var theOne = $('.the-one');
var parent = theOne.closest('.group');
var parentThing = parent.find('.group-thing').first();
var grandparent = parent.parents('.group').first();
var grandparentThing = grandparent.find('.group-thing').first();
// uncommenting these will color the "top thing" and "parent thing" red.
//parentThing.css('background-color','red');
//grandparentThing.css('background-color','red');
// This call alone should color the "top thing" and "parent thing" red, but it doesn't.
setParentChainText(theOne);
});
以及示例的 HTML:
<div class="group">
<div class="group-thing">top thing</div>
<div class="group">
<div class="group-thing">uncle thing</div>
<div class="item">
<div class="child-thing">item</div>
<div class="child-other">other</div>
</div>
<div class="item">
<div class="child-thing">item</div>
<div class="child-other">other</div>
</div>
<div class="item">
<div class="child-thing">item</div>
<div class="child-other">other</div>
</div>
</div>
<div class="group">
<div class="group-thing">parent thing</div>
<div class="item">
<div class="child-thing the-one">The One</div>
<div class="child-other">other</div>
</div>
<div class="item">
<div class="child-thing">item</div>
<div class="child-other">other</div>
</div>
<div class="item">
<div class="child-thing">item</div>
<div class="child-other">other</div>
</div>
</div>
<div class="group">
<div class="group-thing">uncle thing</div>
<div class="item">
<div class="child-thing">item</div>
<div class="child-other">other</div>
</div>
<div class="item">
<div class="child-thing">item</div>
<div class="child-other">other</div>
</div>
<div class="item">
<div class="child-thing">item</div>
<div class="child-other">other</div>
</div>
</div>
</div>
最佳答案
下面的代码让你陷入困境:
if (node.hasClass('group-thing')) {
parent = node.parents('.group').first()
}
这只是再次找到相同的“组”父级,并一遍又一遍地留在第一个组中。
更改为: varparent = node.hasClass('group-thing') ? node.parent().parent() : node.closest('.group');
这是我的 fiddle : http://jsfiddle.net/nhmaggiej/wtdsa5cq/
关于javascript - 如何使用 javascript 或 jquery 爬取 DOM,仅查看直系 parent ,而不查看叔叔/阿姨?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26794924/