Javascript 使用jquery通过类获取元素的不同名称

Javascript 使用jquery通过类获取元素的不同名称,javascript,jquery,Javascript,Jquery,我有以下HTML: 单选按钮列表: 您可以执行以下操作: 演示: 代码: var classNames = []; $('*').each(function() { classNames[$(this).attr('name')] = 1; }); for(var x in classNames) { console.log(x); } 您可以使用jQuery.unique()方法 jQuery.unique($('.required_Mandatory_RbtLst[name!=]'));

我有以下HTML:

单选按钮列表:


您可以执行以下操作:

演示

代码:

var classNames = [];
$('*').each(function() { classNames[$(this).attr('name')] = 1; });
for(var x in classNames) { console.log(x); }

您可以使用jQuery
.unique()
方法

jQuery.unique($('.required_Mandatory_RbtLst[name!=]'));
参考:

试试这个

var names = $("input").map(function(){ return $(this).attr('name'); });
var distinctNames = $.unique(names);
在这里阅读有关map函数的更多信息

简单地说,这个解决方案将元素的名称保存到一个jQuery对象包装的数组中,该数组在上,唯一值保存到一个数组中


映射并不十分必要,因此为了简单起见,您也可以跳过该步骤来进行映射

var cbnames = [];
$('.required_Mandatory_ChkLst[name!=]').each(function() {
    if (!~$.inArray(this.name, cbnames)) cbnames.push(this.name);
});
console.log(cbnames); //["chLst165", "chLst166"]

类似于
过滤器()


我相信你想要的是这个

var mapped = $('.required_Mandatory_ChkLst[name!=], .required_Mandatory_RbtLst[name!=]').map(function() {
    return $(this).attr('name');
});

var unique = mapped.filter(function (i, itm) {
    return i == $.makeArray(mapped).indexOf(itm);
});

console.log(unique);
首先,我们将dom元素的集合映射到具有所述元素名称的字符串值的集合。 其次,我们过滤这个名称集合,使其只包含唯一的实例


注意:其他答案建议使用jQuery.unique。但是,此方法适用于dom元素集合,在您的情况下,所有这些元素都是唯一的。

您尝试过吗?元素不同,名称属性相同。IMO,
.unique
将返回相同的数组。@永不后退:选择器将返回所有6个元素。。我尝试了jQuery.unique($('.required_Mandatory_RbtLst[name!=])@你试过我的答案了吗
unique()
应该使用dom元素数组作为参数,而不是jquery对象。@Johan:这也不起作用,但您建议的新方法正在起作用。不客气<代码>=]花点时间标记一个,这样人们就会知道您的问题已经解决。谢谢您的回答。工作得很好。谢谢你的帮助answer@rohith86如果你喜欢不同的答案,请选择投票。
jQuery.unique($('.required_Mandatory_RbtLst[name!=]'));
var names = $("input").map(function(){ return $(this).attr('name'); });
var distinctNames = $.unique(names);
var cbnames = [];
$('.required_Mandatory_ChkLst[name!=]').map(function() {
    return this.name;
}).each(function(i, str) {
    if (!~$.inArray(str, cbnames)) cbnames.push(str);
});
console.log(cbnames); //["chLst165", "chLst166"]
var cbnames = [];
$('.required_Mandatory_ChkLst[name!=]').each(function() {
    if (!~$.inArray(this.name, cbnames)) cbnames.push(this.name);
});
console.log(cbnames); //["chLst165", "chLst166"]
$(function(){
    var names = [];
    $('.required_Mandatory_RbtLst').each(function(){

        if($.inArray($(this).prop('name'), names) === -1)
            names.push($(this).prop('name'));
    });

    console.log($(names));
});​
var mapped = $('.required_Mandatory_ChkLst[name!=], .required_Mandatory_RbtLst[name!=]').map(function() {
    return $(this).attr('name');
});

var unique = mapped.filter(function (i, itm) {
    return i == $.makeArray(mapped).indexOf(itm);
});

console.log(unique);