如何使用jquery检查输入类型是否为radio

Dar*_*rcy 33 html jquery

我想根据类型不同地处理html元素.

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

我试过了:

if ($('#myElement').is(':radio')) {
    ....//code here
}
Run Code Online (Sandbox Code Playgroud)

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

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

编辑:

if ($('#myElement').is(':radio')) {
    ....//code here
}
Run Code Online (Sandbox Code Playgroud)

但是我的单选按钮没有id属性,它们只有一个name属性,这就是为什么它不起作用.

我将代码更改为:

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

use*_*716 48

只要元素被加载,这应该工作.

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

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

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

    el.filter(':checkbox').change(function() {
        // other code here
    });
});
Run Code Online (Sandbox Code Playgroud)

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