【发布时间】:2010-12-04 16:14:56
【问题描述】:
我在一个 HTML 页面上有几个元素具有相同的类 - 但它们是不同的元素类型。我想在循环遍历元素时找出元素的标签名称 - 但 .attr 不采用“标签”或“标签名称”。
这就是我的意思。考虑页面上的这些元素:
<h1 class="rnd">First</h1>
<h2 id="foo" class="rnd">Second</h2>
<h3 class="rnd">Third</h3>
<h4 id="bar" class="rnd">Fourth</h4>
现在我想运行这样的东西来确保我的元素都有一个 id 如果尚未定义:
$(function() {
$(".rnd").each(function(i) {
var id = $(this).attr("id");
if (id === undefined || id.length === 0) {
// this is the line that's giving me problems.
// .attr("tag") returns undefined
$(this).attr("id", "rnd" + $(this).attr("tag") + "_" + i.toString());
}
});
});
我想要的结果是 H2 和 H4 元素的 id 为
rndh2_1
rndh4_3
分别。
关于如何发现“this”表示的元素的标签名称有什么想法吗?
【问题讨论】:
标签: javascript jquery