jQuery可以提供标签名称吗?

我在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_1

rndh4_3

分别。


关于如何发现“ this”表示的元素的标签名称的任何想法?


javascript jquery


慕沐林林
浏览 554回答 3
3回答

白猪掌柜的

您可以尝试以下方法:if($(this).is('h1')){&nbsp; doStuff();}

侃侃尔雅

由于我之前曾经遇到过这个问题,并且对我的情况没有帮助(我没有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;&nbsp; &nbsp; &nbsp;// will get you the original DOM element object
打开App,查看更多内容
随时随地看视频慕课网APP