jQuery 如何使用jquery检查输入类型是否为收音机

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

how to check if input type is radio using jquery

jqueryhtml

提问by Darcy

I want to handle html elements differently based on their type.

我想根据它们的类型以不同的方式处理 html 元素。

Using jquery, how do I check to see if an input type is a radio button?

使用 jquery,如何检查输入类型是否为单选按钮?

I've tried:

我试过了:

if ($('#myElement').is(':radio')) {
    ....//code here
}

and

if ($('#myElement').is("input[type='radio']")) {
    ....//code here
}

Neither of these worked. Any ideas?

这些都没有奏效。有任何想法吗?

EDIT:

编辑:

if ($('#myElement').is(':radio')) {
    ....//code here
}

works, but my radio buttons don't have the id attribute, they only have a name attribute, which is why it did not work.

有效,但我的单选按钮没有 id 属性,它们只有一个 name 属性,这就是它不起作用的原因。

I changed my code to:

我将代码更改为:

if ($('input[name=' + myElement + ']').is(":radio")) {
    ....//code here
}

回答by user113716

That should work as long as the elements are loaded.

只要加载了元素,这应该可以工作。

// Ensure the DOM is ready
$(function() {
    if ($('#myElement').is(':radio')) {
        //code here
    }
});

If you're assigning handlers based on type, another approach would be to use .filter().

如果您根据类型分配处理程序,另一种方法是使用.filter().

$(function() {
    var el = $('#myElement');
    el.filter(':radio').change(function() {
        //code here
    });

    el.filter(':checkbox').change(function() {
        // other code here
    });
});

If it doesn't pass the filter(), the handler won't be assigned.

如果它没有通过filter(),则不会分配处理程序。

回答by Mark Baijens

That should work you can try to use filter this way instead

那应该可行,您可以尝试以这种方式使用过滤器

if ($('#myElement').filter(':radio').size() > 0) {
    ....//code here
}
and

if ($('#myElement').filter("input[type='radio']").size() > 0) {
    ....//code here
}

Or

或者

$('#myElement:radio').each(function() {
        ....//code here
});

Udate:Are you also sure that the id is unique in the page? If you want to select more as 1 element you can use a class instead.

Udate:你也确定这个id在页面中是唯一的吗?如果您想选择更多作为 1 个元素,您可以改用一个类。

回答by guest but not last

if($('#my-element').attr('type') == 'radio')