我想根据它们的类型来处理html元素的不同。
使用jquery,如何查看输入类型是单选按钮吗?
我试过了:
if ($('#myElement').is(':radio')) {
....//code here
}
和
if ($('#myElement').is("input[type='radio']")) {
....//code here
}
这两个都没有。有任何想法吗?
编辑:
if ($('#myElement').is(':radio')) {
....//code here
}
作品,但是我的单选按钮没有id属性,它们只有一个name属性,这就是为什么它不起作用。
我将我的代码更改为:
if ($('input[name=' + myElement + ']').is(":radio")) {
....//code here
}
解决方法
只要元素被加载就可以工作。
// Ensure the DOM is ready
$(function() {
if ($('#myElement').is(':radio')) {
//code here
}
});
如果您根据类型分配处理程序,另一种方法将是使用.filter()。
$(function() {
var el = $('#myElement');
el.filter(':radio').change(function() {
//code here
});
el.filter(':checkBox').change(function() {
// other code here
});
});
如果没有通过filter(),则不会分配处理程序。