使用jQuery获取元素类型

本文翻译自:Get element type with jQuery

Is it possible, using jQuery, to find out the type of an element with jQuery? 是否可以使用jQuery通过jQuery找出元素的类型? For example, is the element a div, span, select, or input? 例如,元素是div,span,select还是input?

For example, if I am trying to load values into a drop-down list with jQuery, but the same script can generate code into a set of radio buttons, could I create something like: 例如,如果我尝试使用jQuery将值加载到下拉列表中,但是相同的脚本可以将代码生成到一组单选按钮中,我可以创建类似于:

$('.trigger').live('click', function () {
   var elementType = $(this).prev().attr(WHAT IS IT);
});

Given a drop-down list with a button next to it with the trigger class, my elementType variable should return select upon the button being pressed. 给定一个带有触发器类旁边带有按钮的下拉列表,我的elementType变量应该在按下按钮时返回select


#1楼

参考:https://stackoom.com/question/ZCDu/使用jQuery获取元素类型


#2楼

你也可以使用:

$("#elementId").get(0).tagName

#3楼

use get(0).tagName. 使用get(0).tagName。 See this link 看到这个链接


#4楼

Use Nodename over tagName : 在tagName上使用Nodename:

nodeName contains all functionalities of tagName, plus a few more. nodeName包含tagName的所有功能,以及更多功能。 Therefore nodeName is always the better choice. 因此nodeName始终是更好的选择。

see DOM Core DOM Core


#5楼

As Distdev alluded to, you still need to differentiate the input type. 正如Distdev所提到的,您仍然需要区分输入类型。 That is to say, 也就是说,

$(this).prev().prop('tagName');

will tell you input , but that doesn't differentiate between checkbox/text/radio. 会告诉你input ,但这不区分复选框/文本/收音机。 If it's an input, you can then use 如果是输入,则可以使用

$('#elementId').attr('type');

to tell you checkbox/text/radio, so you know what kind of control it is. 告诉你复选框/文本/广播,所以你知道它是什么样的控制。


#6楼

you can use .is() : 你可以使用.is()

  $( "ul" ).click(function( event ) {
      var target = $( event.target );
      if ( target.is( "li" ) ) {
         target.css( "background-color", "red" );
      }
  });

see source 来源

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值