元素的jQuery标签名称
问题描述:
我试图在jQuery中获取一个元素标签名称.
I'm try to get an elements tag name in jQuery.
我有以下html:
<div class="section" id="New_Revision">
<h1>New Revision <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:
And javascript:
$(".edit").click(function(){
$(this).closest("div.section").children().each(function(){
alert($(this).tagName + " - " + $(this).html());
});
})
我已经尝试过$(this).tagName
,$(this).nodeName
和$(this).attr("tag")
,如以下问题所述:
I've tried $(this).tagName
, $(this).nodeName
and $(this).attr("tag")
as noted in this question: Can jQuery provide the tag name?
但是我总是得到undefined
作为回报. html()
正确输出.为什么无法获取每个元素的标签名称?
But I'm always getting undefined
in return. The html()
outputs correctly. Why can't I get the tag name of each element?
答
尝试
this.nodeName
而不是$(this).nodeName
this
引用DOM元素本身,而$(this)
将该元素包装在jQuery对象中.
this
refers to the DOM element itself and $(this)
wraps the element up in a jQuery object.
编辑
如果您需要Jquery方法,则可以使用
If you require Jquery approach you can use
$(this).prop("tagName")