首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >jQuery能提供标记名吗?

jQuery能提供标记名吗?
EN

Stack Overflow用户
提问于 2009-10-07 15:24:13
回答 10查看 132.2K关注 0票数 117

我在一个HTML页面上有几个元素,它们具有相同的类-但它们是不同的元素类型。我想在遍历元素时找出元素的标记名--但是.attr不接受" tag“或"tagname”。

这就是我的意思。考虑页面上的这些元素:

代码语言:javascript
复制
<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的话):

代码语言:javascript
复制
$(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为

代码语言:javascript
复制
rndh2_1
rndh4_3

分别使用。

关于如何发现由"this“表示的元素的标记名,有什么想法吗?

EN

回答 10

Stack Overflow用户

回答已采纳

发布于 2009-10-07 15:25:58

代码语言:javascript
复制
$(this).attr("id", "rnd" + $(this).attr("tag") + "_" + i.toString());

应该是

代码语言:javascript
复制
$(this).attr("id", "rnd" + this.nodeName.toLowerCase() + "_" + i.toString());
票数 110
EN

Stack Overflow用户

发布于 2009-10-07 15:27:42

你可以试试这个:

代码语言:javascript
复制
if($(this).is('h1')){
  doStuff();
}

有关is()的更多信息,请参阅docs

票数 166
EN

Stack Overflow用户

发布于 2010-11-17 09:23:13

因为我以前遇到过这个问题,但它对我的情况没有帮助(我没有this,而是有一个jQuery选择器实例)。调用get()将获得HTML元素,通过该元素可以获得上面提到的nodeName

代码语言:javascript
复制
this.nodeName; // In a event handler, 'this' is usually the element the event is called on

代码语言:javascript
复制
$('.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
票数 53
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1532331

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档