我在HTML页面上有几个具有相同类的元素 - 但它们是不同的元素类型.我想在循环它们时找出元素的标记名称 - 但.attr不带"tag"或"tagname".
这就是我的意思.在页面上考虑以下元素:
<h1 class="rnd">First</h1>
<h2 id="foo" class="rnd">Second</h2>
<h3 class="rnd">Third</h3>
<h4 id="bar" class="rnd">Fourth</h4>
Run Code Online (Sandbox Code Playgroud)
现在我想运行这样的东西,以确保我的元素都有一个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());
}
});
});
Run Code Online (Sandbox Code Playgroud)
我想要的结果是H2和H4元素的id值为
rndh2_1
rndh4_3
Run Code Online (Sandbox Code Playgroud)
分别.
关于如何发现"this"所代表的元素的标签名称的任何想法?