使用jQuery/Javascript创建集合中所有元素的列表 [英] Use jQuery/Javascript to create a list of all elements in a set
问题描述
我想使用Javascript遍历一组元素,并为每个元素创建一个标签列表,因此,如果该组元素如下:
I want to use Javascript to loop through a set of elements, and create a list of labels for each one, so if the set of elements were as follows:
<h1>Title</h1>
<h2>Subheading</h2>
<p>Paragraph of text...</p>
它会给我以下内容:
<ol>
<li>h1</li>
<li>h2</li>
<li>p</p>
<ol>
jQuery/Javascript是否有可能以字符串形式返回元素的类型,如果可以的话,我将如何处理呢?
Is it possible for jQuery/Javascript to return an element's type as a string, and if so how would I go about it?
推荐答案
这与我做过的最干净的代码相去甚远,但是它可以工作:
This is far from the cleanest piece of code I've ever done, but it works:
function generateList(rootElement) {
var rootElementItem = $("<li>" + rootElement.get(0).tagName + "</li>");
if (rootElement.children().size() > 0) {
var list = $("<ol />");
rootElement.children().each(function() {
list.append(generateList($(this)));
});
rootElementItem.append(list);
}
return rootElementItem;
}
var listOfElements = generateList($("body"));
$("body").append($("<ol/>").append(listOfElements));
演示: http://jsfiddle.net/jonathon/JvQKz/
它基于先前给出的this.tagName
答案,但是它也检查子级.这样,它将建立给定元素的层次结构视图.该方法不会生成封闭的<ol/>
标记,因此只能将其附加到现有标记中.
It builds upon the this.tagName
answer that was previously given, but it checks for children also. This way it will build up a hierarchical view of the element given. The method doesn't generate the enclosing <ol/>
tag so that it can just be appended to an existing one.
这篇关于使用jQuery/Javascript创建集合中所有元素的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!