我在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
白猪掌柜的
侃侃尔雅
相关分类