为了账号安全,请及时绑定邮箱和手机立即绑定

jQuery可以提供标签名称吗?

jQuery可以提供标签名称吗?

慕沐林林 2019-11-30 12:49:02
我在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_1rndh4_3分别。关于如何发现“ this”表示的元素的标签名称的任何想法?javascript jquery
查看完整描述

3 回答

?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

您可以尝试以下方法:


if($(this).is('h1')){

  doStuff();

}


查看完整回答
反对 回复 2019-11-30
?
侃侃尔雅

TA贡献1801条经验 获得超15个赞

由于我之前曾经遇到过这个问题,并且对我的情况没有帮助(我没有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


查看完整回答
反对 回复 2019-11-30
  • 3 回答
  • 0 关注
  • 546 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信