使用 jQuery 获取元素类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8388470/
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-27 10:27:35  来源:igfitidea点击:

Get element type with jQuery

jqueryelement

提问by Jamie Hartnoll

Is it possible, using jQuery, to find out the type of an element with jQuery? For example, is the element a div, span, select, or input?

是否有可能使用 jQuery 找出带有 jQ​​uery 的元素的类型?例如,元素是 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 triggerclass, my elementTypevariable should return selectupon the button being pressed.

给定一个下拉列表,旁边有一个带有触发器类的按钮,我的elementType变量应该select在按下按钮时返回。

回答by adeneo

Getting the element type the jQuery way:

以 jQuery 方式获取元素类型:

var elementType = $(this).prev().prop('nodeName');

doing the same without jQuery

在没有 jQuery 的情况下做同样的事情

var elementType = this.previousSibling.nodeName;

Checking for specific element type:

检查特定元素类型:

var is_element_input = $(this).prev().is("input"); //true or false

回答by Ali

also you can use:

你也可以使用:

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

回答by Distdev

you should use tagNameproperty and attr('type')for inputs

你应该使用tagName属性和attr('type')输入

回答by James Toomey

As Distdev alluded to, you still need to differentiate the input type. That is to say,

正如 Distdev 所提到的,您仍然需要区分输入类型。也就是说,

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

will tell you input, but that doesn't differentiate between checkbox/text/radio. If it's an input, you can then use

会告诉你input,但这并不能区分复选框/文本/收音机。如果是输入,则可以使用

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

to tell you checkbox/text/radio, so you know what kind of control it is.

告诉你checkbox/text/radio,这样你就知道是什么控件了。

回答by Mohammed Sufian

you can use .is():

你可以使用.is()

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

see source

来源

回答by Amar

use get(0).tagName. See this link

使用 get(0).tagName。看这个链接

回答by Mike Rifgin

Use Nodename over tagName :

在 tagName 上使用 Nodename :

nodeName contains all functionalities of tagName, plus a few more. Therefore nodeName is always the better choice.

nodeName 包含 tagName 的所有功能,以及更多功能。因此 nodeName 始终是更好的选择。

see DOM Core

DOM 核心