我在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_1rndh4_3分别。关于如何发现“ this”表示的元素的标签名称的任何想法?javascript jquery
3 回答

侃侃尔雅
TA贡献1801条经验 获得超16个赞
由于我之前曾经遇到过这个问题,并且对我的情况没有帮助(我没有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
添加回答
举报
0/150
提交
取消