4

我已经动态呈现了 HTML,其中列出了数量不确定的单选按钮,其名称代表数据库中的一些 id。

我需要收集收音机的所有唯一名称。

这是一个例子:

<input name="721" type="radio" value="A" />        
<input name="721" type="radio" value="I" />     

<input name="722" type="radio" value="A" />        
<input name="722" type="radio" value="I" />     

<input name="723" type="radio" value="A" />        
<input name="723" type="radio" value="I" />     

不需要检查无线电,因此使用 selected 或 checked 属性将不起作用。

有没有一种优雅的方法可以使用 jQuery 获取收音机的所有唯一名称?我知道我可以遍历每个收音机,但我希望 jQuery 有一种更优雅的方式来做到这一点?

4

9 回答 9

6

jsBin 演示

var arr = [];

$.each( $('input:radio'), function(){

  var myname= this.name;
  if( $.inArray( myname, arr ) < 0 ){
     arr.push(myname); 
  }

});

alert(arr); // 721,722,723
于 2013-01-01T18:04:31.383 回答
1
var names = $('input[type=radio]').map(function() {
    return this.name
}).get(); // create an array of names

var unique = $.grep(names, function(v, i) {
    return $.inArray(v, names) === i
}); // filter unique values

http://jsfiddle.net/WnHvz/

于 2013-01-01T18:08:18.803 回答
1

要获得唯一名称,您可以使用map()构建所有名称的数组,然后将$.grep()$.inArray()组合以删除重复项。

就像是:

var allNames = $("input[type=radio]").map(function() {
    return $(this).attr("name");
}).get();

var uniqueNames = $.grep(allNames, function(name, index) {
    return $.inArray(name, allNames) == index;
});
于 2013-01-01T18:08:32.287 回答
0
$('input:radio').each(function(){
    // do something
 });
于 2013-01-01T18:02:10.090 回答
0

仅供参考 - 您发布的 html 没有唯一的名称。每个都有两个......但这是你如何获得它们:

$('input[type="radio"]').each(function() {
    alert($(this).attr('name'));
});​
于 2013-01-01T18:03:09.837 回答
0

如果你想print those names在每个之前radio使用它:

$('input[type="radio"]').each(function() {
    $(this).before($(this).attr('name'));
});​

试试小提琴:http: //jsfiddle.net/teLjg/

于 2013-01-01T18:07:29.683 回答
0

只需尝试循环并获取所有名称并将其存储在一个数组中......然后通过使用过滤器方法,您可以过滤唯一值......

可以说,

var array=[your array values];

var unique_val = array.filter(function(value,iter,array){
    return iter == array.indexOf(value);
});

这可能有效...

于 2013-01-01T18:12:45.343 回答
0

首先获取无线电项目的节点列表:

const radios = document.querySelectorAll("input[type="radio"])

然后得到一个名字的数组,然后用它们做一个集合,一个定义的集合只包含唯一的条目:

const nameSet = new Set(Array.from(radios).map( el => el.name))
于 2021-09-02T20:17:50.417 回答
-1

我认为你们这么快并且喜欢 jQuery,呵呵。如果有 2 个单选按钮,这可能会对您有所帮助, http://jsfiddle.net/BTcrR/看看这个

$(function() {
    // list of 
    var rediobuttonsName = new Array();
    // you can use :odd | :even
    $('input[type="radio"]').not(':odd').map(function(n, elem) {

       rediobuttonsName.push(elem.name);
       // or  you can use the context of object this
       // this.name

   });

   alert(rediobuttonsName);
});​

或者您可以使用 .not(":odd") 并检查数组是否具有名称的值。;)

于 2013-01-01T18:31:55.277 回答