本文翻译自: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始终是更好的选择。
#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" );
}
});