使用 jQuery/Javascript 创建集合中所有元素的列表
我想使用 Javascript 循环访问一组元素,并为每个元素创建一个标签列表,因此如果该组元素如下所示:
<h1>Title</h1>
<h2>Subheading</h2>
<p>Paragraph of text...</p>
它会给我以下内容:
<ol>
<li>h1</li>
<li>h2</li>
<li>p</p>
<ol>
jQuery/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>
It would give me the following:
<ol>
<li>h1</li>
<li>h2</li>
<li>p</p>
<ol>
Is it possible for jQuery/Javascript to return an element's type as a string, and if so how would I go about it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这远不是我做过的最干净的代码,但它有效:
演示: http://jsfiddle .net/jonathon/JvQKz/
它建立在之前给出的
this.tagName
答案的基础上,但它也会检查子项。这样它将建立给定元素的分层视图。该方法不会生成封闭的标记,因此它只能附加到现有标记。
This is far from the cleanest piece of code I've ever done, but it works:
Demo: http://jsfiddle.net/jonathon/JvQKz/
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.我希望这个简单的解决方案有所帮助:
http://jsfiddle.net/neopreneur/n7xJC/
-html-
-js-
这适用于假设你有一个格式正确且带有 body 标记的 HTML 文档。
I hope this simple solution helps:
http://jsfiddle.net/neopreneur/n7xJC/
-html-
-js-
This works assuming you have a properly formed HTML document with a body tag.
示例
example