2013-12-03 45 views
0

问:确定多个选择列表是否具有相同的最简单/最有效的方法是什么selectedIndex检查SelectedIndex匹配多个选择

背景资料: 我有一个页面上的多个(最多200)选择列表 - 所有类tariff,我需要检查,他们都具有相同的selectedIndex

我的第一种方法是使用循环每录制前值 - 确保每一个选择匹配的 - 但它只是似乎效率不高。例如

var tariffSelected; 
var first = true; 
$('.tariff').each(function() { 
    if (first) { 
     // store first value 
     tariffSelected = $(this).prop('selectedIndex'); 
     first = false; 
    } 
    if (tariffSelected !== $(this).prop('selectedIndex')) { 
     // they don't match 
    } 
}); 

回答

2

我只想确认选择的数量是一样的选择与selectedIndex处的数匹配第一个选择,例如:

var allTariffs = $('.tariff'); 
var indexToMatch = allTariffs.eq(0).prop('selectedIndex'); 

var matchingTariffs = allTariffs.filter(function() { 
    return $(this).prop('selectedIndex') === indexToMatch; 
}); 

var allMatch = allTariffs.length === matchingTariffs.length; 
+0

+1正是我一直在寻找...感谢(当计时器到期会接受) – ManseUK

+1

'matchingTariffs.length'? ? –

+0

@ A.Wolff刚刚注意到,当我测试它时... – ManseUK

1

这里是一个工作示例

http://jsfiddle.net/q89Tf/

var s = $("select.tariff"); 
var firstVal = $("select").first().prop("selectedIndex"); 
var ss = $('select').filter(function() { 
    return this.selectedIndex === firstVal; 
}).length === s.length; 
+0

不知道为什么这会被低估 - 看起来工作正常...... +1谢谢 – ManseUK

+0

我低估了这一点,因为它与我的答案完全一样(与之后17分钟。 – jbabey

+0

对不起,我真的没有复制你,我开始研究它,并没有刷新页面之前发布。 –