【问题标题】:Can jQuery provide the tag name?jQuery 可以提供标签名称吗?
【发布时间】:2010-12-04 16:14:56
【问题描述】:

我在一个 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


【解决方案1】:

而是简单地做:

$(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
      // change the below line...
      $(this).attr("id", "rnd" + this.tagName.toLowerCase() + "_" + i.toString()); 
  });
});

【讨论】:

    【解决方案2】:

    考虑快速的 FILTER 方法:

    $('.rnd').filter('h2,h4')
    

    返回:

    [<h2 id=​"foo" class=​"rnd">​Second​</h2>​, <h4 id=​"bar" class=​"rnd">​Fourth​</h4>​]
    

    所以:

    $('.rnd').filter('h2,h4').each(function() { /*...$(this)...*/ });
    

    【讨论】:

      【解决方案3】:

      解决问题的最佳方法是将$(this).attr("tag") 替换为this.nodeName.toLowerCase()this.tagName.toLowerCase()

      两者产生完全相同的结果!

      【讨论】:

        【解决方案4】:

        是的。您可以使用以下代码:

        this.tagName
        

        【讨论】:

          【解决方案5】:

          我只是为了另一个问题而写的,我认为它也可以帮助你们。

          用法:

          • onclick="_DOM_Trackr(this);"

          参数:

          1. 要跟踪的 DOM 对象
          2. 返回/警报开关(可选,默认=警报)

          源代码:

          function _DOM_Trackr(_elem,retn=false)
          {
              var pathTrackr='';
              var $self=$(_elem).get(0);
              while($self && $self.tagName)
              {
                  var $id=($($self).attr("id"))?('#'+$($self).attr("id")):'';
                  var $nName=$self.tagName;
                  pathTrackr=($nName.toLowerCase())+$id+((pathTrackr=='')?'':' > '+(pathTrackr));
                  $self=$($self).parent().get(0);
              }
              if (retn)
              {
                  return pathTrackr;
              }
              else
              {
                  alert(pathTrackr);
              }
          }
          

          【讨论】:

          • 示例输出:html &gt; body &gt; div#coreApp &gt; div#productpage &gt; div#productpage-wrapper &gt; div &gt; div &gt; div &gt; div &gt; div#pthumb12 &gt; form#thumb_uploader_src &gt; input
          • 另一个用法示例: $('*').each(function(_i,_e){$(_e).attr('title',_DOM_Trackr(_e,true));});
          【解决方案6】:
          you can try:
          jQuery(this).get(0).tagName;
          or
          jQuery(this).get(0).nodeName;
          

          注意: 用您的选择器(h1、h3 或 ...)替换它

          【讨论】:

            【解决方案7】:

            您可以在整个页面上获取html元素标签名称。

            你可以使用:

                    $('body').contents().on("click",function () {
                      var string = this.tagName;
                      alert(string);
                     });
            

            【讨论】:

              【解决方案8】:

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

              【讨论】:

              • 这正是我所需要的。在我的设计中,我有方便的 jquery 元素,但没有原始的 HTML DOM 元素。这对我有用。
              • 我认为这是回答这个问题的确切答案。
              【解决方案9】:

              由于这是您在 google 上使用 jquery tagname first child 作为查询的问题,我将发布另一个示例:

              <div><p>Some text, whatever</p></div>
              
              $('div').children(':first-child').get(0).tagName); // ...and not $('div:first-child')[...]
              

              jquery 结果是一个(大写)标记名:P

              【讨论】:

                【解决方案10】:

                我认为你不能在 jQuery 中使用 nodeName,因为 nodeName 是一个 DOM 属性,而 jQuery 本身没有 nodeName 函数或属性。但根据第一次提到这个nodeName 东西的受访者,这就是我能够解决问题的方法:

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

                注意:this 这里是一个 jQuery 对象。

                【讨论】:

                  【解决方案11】:
                  $(this).attr("id", "rnd" + $(this).attr("tag") + "_" + i.toString());
                  

                  应该是

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

                  【讨论】:

                  • 您需要使用 this.nodeName.toLowerCase(),因为大多数 HTML 文档的 DOM 表示会自动将 nodeName 大写。
                  • this.nodeName 和 this.tagName 似乎都对我有用。谢谢大家!
                  • +1 用于提及 nodeName。有时,jQuery 有点过分了 :-)
                  • +1 jQuery is() 不起作用,因为在 h1、h2 等情况下,如果使用 is(),您必须处理 6 种不同的情况。
                  【解决方案12】:

                  因为我以前曾遇到过这个问题,但它对我的情况没有帮助(我没有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
                  

                  【讨论】:

                  • 页面上的第一个有用的
                  【解决方案13】:

                  你可以试试这个:

                  if($(this).is('h1')){
                    doStuff();
                  }
                  

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

                  【讨论】:

                  • 它可能关心的人:如果您对我的答案投反对票,请告诉我原因,以便我可以改进它并学习未来的 SO 答案。谢谢。
                  • 我也讨厌它。无论如何,我投了赞成票,因为nodeName 返回一个字符串,取决于浏览器,是否大写。
                  • 假设以下内容:您不仅有少量可能的标签,而且可能是 100 多个 html 标签中的任何一个。然后你需要写: $(this).is('sometag') a 100+ 次。我想这就是为什么有些人不赞成你的回答。
                  • 哇...多年来从未见过is('*')。它可能不会回答 OP,但它对我有用,谢谢,@middus!
                  猜你喜欢
                  • 2020-07-15
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2013-04-06
                  • 1970-01-01
                  相关资源
                  最近更新 更多