【问题标题】:jQuery tag name of element元素的jQuery标签名称
【发布时间】:2013-04-06 00:37:24
【问题描述】:

我正在尝试在 jQuery 中获取元素标签名称。

我有以下html:

<div class="section" id="New_Revision">

    <h1>New Revision&nbsp<img alt="Lock_closed" class="edit" data-id="1" src="/assets/lock_closed.svg" /></h1>

    <p>This is a test paragraph.</p>

    <ol class="references">
      <li>test</li>
    </ol>
</div>

还有 javascript:

$(".edit").click(function(){
    $(this).closest("div.section").children().each(function(){
        alert($(this).tagName + " - " + $(this).html());
    });     
})

我已经尝试过 $(this).tagName$(this).nodeName$(this).attr("tag"),如本问题所述:Can jQuery provide the tag name?

但我总是得到undefined 作为回报。 html() 输出正确。为什么获取不到每个元素的标签名?

【问题讨论】:

标签: jquery html tags


【解决方案1】:

试试

this.nodeName 而不是$(this).nodeName

this 指代 DOM 元素本身,$(this) 将元素包装在一个 jQuery 对象中。

编辑

如果你需要 Jquery 方法,你可以使用

$(this).prop("tagName")

【讨论】:

  • 这是使用 javascript 而不是问题中所述的 Jquery。
  • @Floradu 这也是我在这里所说的。DOM 表示文档对象模型。为什么不赞成?
  • 正如我之前所说,他想要的是 Jquery 方法,而不是 Js 方法,我删除了反对意见
  • 谢谢,这是最简单的解决方案。
  • 好吧,如果你真的因为某种原因想要使用 jQuery 函数,你可以使用 $(this).prop('tagName') - 但是使用 this.tagName 更容易ssilas777 说。
【解决方案2】:

你试过了吗:

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

如链接问题所述。 $(this)this

之间也有很大的区别

在浏览器控制台中尝试过,它可以工作:

document.getElementsByTagName("a")[0].tagName // this uses javascript

这使用jquery:

$('a').get(0).nodeName; // this works for jquery

试试这个:

$(".edit").click(function(){
    $(this).closest("div.section").children().each(function(){
        alert(this.tagName + " - " + $(this).html());
    });     
})

【讨论】:

  • 谢谢,但我无法理解如何将其适应上面的 $(this).tagName 代码。
猜你喜欢
  • 2011-07-17
  • 1970-01-01
  • 2018-07-13
  • 2017-05-28
  • 2012-03-16
  • 1970-01-01
  • 1970-01-01
  • 2013-12-24
相关资源
最近更新 更多