我在一个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>
现在,我想运行类似这样的命令,以确保我的元素都有一个id (如果没有定义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“表示的元素的标记名,有什么想法吗?
发布于 2009-10-07 15:25:58
$(this).attr("id", "rnd" + $(this).attr("tag") + "_" + i.toString());
应该是
$(this).attr("id", "rnd" + this.nodeName.toLowerCase() + "_" + i.toString());
发布于 2009-10-07 15:27:42
发布于 2010-11-17 09:23:13
因为我以前遇到过这个问题,但它对我的情况没有帮助(我没有this
,而是有一个jQuery选择器实例)。调用get()
将获得HTML元素,通过该元素可以获得上面提到的nodeName
。
this.nodeName; // In a event handler, 'this' is usually the element the event is called on
或
$('.hello:first-child').get(0).nodeName; // Use 'get' or simply access the jQuery Object like an array
$('.hello:first-child')[0].nodeName; // will get you the original DOM element object
https://stackoverflow.com/questions/1532331
复制相似问题