Javascript 检查 DOM 元素是否为复选框

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

Check if DOM Element is a checkbox

javascriptjquerydom

提问by Nipuna

How can I check if a given DOM element is a a checkbox.

如何检查给定的 DOM 元素是否为复选框。

Scenario:

设想:

I have a set of textboxes and checkboxes in which the values are assigned dynamically. I don't have a way to identify if the DOM element is a checkbox or a textbox.

我有一组文本框和复选框,其中的值是动态分配的。我无法确定 DOM 元素是复选框还是文本框。

采纳答案by Salman A

If you're using jQuery, you can use the :checkboxpseudo-class selector along with ismethod:

如果您使用 jQuery,则可以将:checkbox伪类选择器与is方法一起使用:

if($("#that-particular-input").is(":checkbox")) {
}

回答by Fabrizio Calderan

Using only vanilla javascript you could do

只使用 vanilla javascript 你可以做

if (el.type && el.type === 'checkbox') {
   ...
}

or even shorter

甚至更短

if ((el || {}).type === 'checkbox') {
   ...
}

or in modern browsers you could use matches()

或在您可以使用的现代浏览器中 matches()

if (el.matches('[type="checkbox"]') {
    ...
}

回答by Leonid

Checks anything

检查任何东西

function isCheckbox (element) {
   return element instanceof HTMLInputElement 
      && element.getAttribute('type') == 'checkbox'
}

回答by jbrtrnd

if( $(element)[0].type == "checkbox" ) {

}

OR

或者

if( $(element).is(':checkbox') ) {

}

回答by Andreas

if (<DOMNode>.type === "checkbox") {
    // ...
}

回答by Jon

Take a look at the checkbox selector.

看看复选框选择器

var checkboxes = $("form input:checkbox");

You can tell what type an input is like this:

您可以这样判断输入是什么类型:

if ($(".your-input").is(":text"))
{
    // Textbox
}
else if ($(".your-input").is(":checkbox"))
{
    // Checkbox
}

回答by thecodeparadox

Try this;

尝试这个;

  $(element).is(':checkbox');

here elementis selector to your element

element是您的选择器element

if(  $(element).is(':checkbox') ) {
  // do something
}

回答by elclanrs

jQuery is():

jQuery is()

if ($el.is(':checkbox')) { ... }

回答by tarashish

You can use the pseudo-selector :checkbox with a call to jQuery's is function:

您可以使用伪选择器 :checkbox 调用 jQuery 的 is 函数:

$('#myinput').is(':checkbox')

$('#myinput').is(':checkbox')

回答by AO_

You should have a decent naming convention which allows you to know if an element is a checkbox from just seeing it's id or name. e.g. "chkMyCheckbox"

您应该有一个体面的命名约定,它允许您仅通过查看元素的 id 或名称就知道它是否是一个复选框。例如“chkMyCheckbox”