jQuery 中是否有一些方法可以获取所有嵌套的子项?我的意思是来自所有嵌套级别的完整集合,这样我就不需要递归调用函数。
这是我的功能
$.fn.extend({
compressElementsWidth: function() {
var range = { min: 9999, max: 0 };
console.log( $(this).contents() );
$(this).contents().filter(
function() {
if (this.nodeType == 3 )
return this.nodeValue && this.nodeValue.replace(/\s{1,6}/,'') ? $(this) : null;
else
return this.nodeName.match(/IMG|A|GROUP|FIELDSET|INPUT|SELECT|TEXTAREA|BUTTON|SUBMIT/) ? $(this) : null;
}).each(function(e) {
var left = $(this).position();
if (p.left < range.min )
range.min = p.left;
var right = p.left + $(this).width;
if ( right > range.max )
range.max = right;
});
var max_width = range.max - range.min;
$(this).contents().filter(
function()
{
if (this.nodeType == 3 )
return this.nodeValue && this.nodeValue.replace(/\s{1,6}/,'') ? $(this) : null;
else
return this.nodeName.match(/IMG|A|GROUP|FIELDSET|INPUT|SELECT|TEXTAREA|BUTTON|SUBMIT/) ? $(this) : null;
}).each(function(e) {
$(this).css("max-width:", max_width );
});
}
});
window.onload = function() {
$("div.column-right-outer").compressElementsWidth();
};
所以我需要获取 div.column-right-outer 中的所有元素。您可以在 this page 上测试此代码, 只需保存它并包含 jQuery 和上面的代码。例如在博客存档中,有大量链接列表,我需要获取所有链接和右栏下的所有可见文本。如果集合中有图像或表单元素,我也需要它们。
最佳答案
method in JQuery to get all nested children
您可以使用 all selector : "*"
以多种方式将其与父元素结合:
var nodes = $("div.column-right-outer *");
var nodes = $("div.column-right-outer > *");
var nodes = $("div.column-right-outer").find("*");
如果您需要所有项目,则不要申请父级:
var nodes = $("*")
fiddle 示例:https://jsfiddle.net/9xted244/
.contents()
类似于“*”,将包含文本和注释
关于javascript - 如何使用 jQuery 获取所有嵌套元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39275325/