收音机上的attr()返回:undefined不是函数

时间:2015-01-24 18:18:36

标签: javascript each radio attr

我有这段代码

$.each($('input:checked', '#components-holder'), function(index, input){
    console.log(input.attr('value'));
});

我收到了这个错误:

undefined is not a function

如何迭代我页面中的所有收音机并获得价值?

1 个答案:

答案 0 :(得分:1)

作为input发送给回调的对象不是 jQuery对象,因此您无法使用jQuery方法。您需要将其转换为jQuery对象以使用jQuery方法:

console.log($(input).attr('value'));

或使用原生DOM属性:

console.log(input.value);

或者,您可能希望使用map来获取适当的值:

var values = $('#components-holder input:checked').map(function(index, input) {
    return input.value;
}).get();

values现在是一个包含所有相关值的数组。