jQuery 元素的jQuery标签名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15989066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:08:48  来源:igfitidea点击:

jQuery tag name of element

jqueryhtmltags

提问by Ryan King

I'm try to get an elements tag name in jQuery.

我试图在 jQuery 中获取元素标记名称。

I have the following html:

我有以下 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>

And javascript:

和 javascript:

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

I've tried $(this).tagName, $(this).nodeNameand $(this).attr("tag")as noted in this question: Can jQuery provide the tag name?

我试过$(this).tagName$(this).nodeName$(this).attr("tag")在这个问题指出:灿提供的jQuery标签的名字吗?

But I'm always getting undefinedin return. The html()outputs correctly. Why can't I get the tag name of each element?

但我总是得到undefined回报。在html()正常输出。为什么我无法获得每个元素的标签名称?

回答by ssilas777

Try

尝试

this.nodeNameinstead of $(this).nodeName

this.nodeName代替 $(this).nodeName

thisrefers to the DOM element itself and $(this)wraps the element up in a jQuery object.

this引用 DOM 元素本身并将元素$(this)包装在 jQuery 对象中。

EDIT

编辑

If you require Jquery approach you can use

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

$(this).prop("tagName")

回答by radu florescu

Have you tried:

你有没有尝试过:

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

As stated in the linked question. Also there is a big difference between $(this)and this

如链接问题所述。$(this)this之间也有很大的不同

Tried this in the browser console and it works:

在浏览器控制台中尝试过这个,它有效:

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

this uses jquery:

这使用jquery:

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

try this:

尝试这个:

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