jQuery可以提供标签名称吗?

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()的更多信息,请参阅文档.

  • 它可能涉及到谁:如果你拒绝我的答案,请告诉我为什么这样我可以改进它并学习未来的答案.谢谢. (11认同)
  • 我也讨厌它.无论如何我赞成,因为`nodeName`返回一个字符串,取决于浏览器,是否为大写字母. (3认同)
  • 假设以下内容:您不仅可以选择少量可能的标签,而且可以是100多个html标签中的任何一个.然后你需要写:$(this).is('sometag')100次以上.我想这就是为什么有些人低估了你的答案. (2认同)

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)

  • 您需要使用this.nodeName.toLowerCase(),因为大多数HTML文档的DOM表示会自动将nodeName大写. (18认同)
  • 提及nodeName的+1.有时,jQuery太过分了:-) (5认同)
  • +1 jQuery is()不能完成这项工作,因为在h1,h2等情况下,如果使用is(),则必须处理6种不同的情况. (2认同)

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)


Bij*_*gta 47

$(this).prop('tagName');如果您使用的是jQuery 1.6或更高版本,也可以使用 它.