jQuery可以提供标签名称吗? [英] Can jQuery provide the tag name?

查看:70
本文介绍了jQuery可以提供标签名称吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在HTML页面上有几个具有相同类的元素-但是它们是不同的元素类型.我想在遍历元素时找出元素的标签名称-但是.attr不会使用标签"或标签名称".

I've got several elements on a HTML page which have the same class - but they're different element types. I want to find out the tag name of the element as I loop over them - but .attr doesn't take "tag" or "tagname".

这就是我的意思.在页面上考虑以下元素:

Here's what I mean. Consider these elements on a page:

<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(如果尚未定义的话):

Now I want to run something like this to ensure that my elements all have an id if one wasn't already defined:

$(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为

The result I would like would be that the H2 and H4 elements would then have an id of

rndh2_1
rndh4_3

分别.

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

Any ideas on how I can discover the tag name of the element represented by "this"?

推荐答案

$(this).attr("id", "rnd" + $(this).attr("tag") + "_" + i.toString());

应该是

$(this).attr("id", "rnd" + this.nodeName.toLowerCase() + "_" + i.toString());

这篇关于jQuery可以提供标签名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆