Big*_*gVT 115 javascript jquery
我在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"所代表的元素的标签名称的任何想法?
mid*_*dus 165
你可以试试这个:
if($(this).is('h1')){
doStuff();
}
Run Code Online (Sandbox Code Playgroud)
有关is()的更多信息,请参阅文档.
Wab*_*son 110
$(this).attr("id", "rnd" + $(this).attr("tag") + "_" + i.toString());
Run Code Online (Sandbox Code Playgroud)
应该
$(this).attr("id", "rnd" + this.nodeName.toLowerCase() + "_" + i.toString());
Run Code Online (Sandbox Code Playgroud)
Sco*_*ood 53
因为我之前曾经遇到过这个问题而且在我的情况下它没有帮助我(我没有a this
,而是有一个jQuery选择器实例).调用get()
将为您提供HTML元素,通过它您可以获得nodeName
上述内容.
this.nodeName; // In a event handler, 'this' is usually the element the event is called on
Run Code Online (Sandbox Code Playgroud)
要么
$('.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
Run Code Online (Sandbox Code Playgroud)