sov*_*ova 8 html javascript jquery
在jQuery中,我如何尽可能地下降到HTML树中?
为简单起见,我只有一条路向下.
(相关但奖励:如何找到具有多个向下路径的最深元素?)
<html>
<table id="table0">
<tr>
<td id="cell0">
<div class"simple"> I want to change this information </div>
</td>
</tr>
</table>
</html>
Run Code Online (Sandbox Code Playgroud)
我想更改名为cell0的单元格的最内层HTML,但我不一定知道里面所有类的名称.是否可以在不知道这些名称的情况下选择这一点?
非常感谢!
paw*_*wel 24
对于单个路径,只需找到没有子节点的元素:
$('body *:not(:has("*"))');
Run Code Online (Sandbox Code Playgroud)
或者,在您更具体的情况下 $('#cell0 *:not(:has("*"))');
对于多个路径 - 如果有多个同样嵌套的节点会怎么样?此解决方案将为您提供具有最多祖先数的所有节点的数组.
var all = $('body *:not(:has("*"))'), maxDepth=0, deepest = [];
all.each( function(){
var depth = $(this).parents().length||0;
if(depth>maxDepth){
deepest = [this];
maxDepth = depth;
}
else if(depth==maxDepth){
deepest.push(this);
}
});
Run Code Online (Sandbox Code Playgroud)
再次,在你的情况下,你可能想要获得表格单元格中最深的元素,所以你要回到单行:
$('#table0 td *:not(:has("*"))');
Run Code Online (Sandbox Code Playgroud)
- 这将返回一个jQuery对象,其中包含表中每个单元格的所有最内层子节点.
我可以通过一个递归函数来做到这一点:
// Returns object containing depth and element
// like this: {depth: 2, element: [object]}
function findDeepestChild(parent) {
var result = {depth: 0, element: parent};
parent.children().each(
function(idx) {
var child = $(this);
var childResult = findDeepestChild(child);
if (childResult.depth + 1 > result.depth) {
result = {
depth: 1 + childResult.depth,
element: childResult.element};
}
}
);
return result;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10702 次 |
| 最近记录: |