早上好。我有一个分为数字部分的表格。有时我需要通过使用它们的部分编号来禁用这些部分中的一部分。现在,当函数接收到一系列节号时,我会运行一个循环来逐一收集它们。有没有更好,更有效的方式来收集编号的部分与jQuery的部分编号?按元素名称索引选择元素
HTML:
<div id="frameContent">
<div id="section1">
<select>
<option value="1" selected="selected">empty (default)</option>
<option value="2" selected="selected">foo</option>
<option value="3" selected="selected">bar</option>
</select>
</div>
<div id="section2">
<select>
<option value="1" selected="selected">empty (default)</option>
<option value="2" selected="selected">foo</option>
<option value="3" selected="selected">bar</option>
</select>
</div>
<div id="section3"><select>
<option value="1" selected="selected">empty (default)</option>
<option value="2" selected="selected">foo</option>
<option value="3" selected="selected">bar</option>
</select></div>
<div id="section4">
<select>
<option value="1" selected="selected">empty (default)</option>
<option value="2" selected="selected">foo</option>
<option value="3" selected="selected">bar</option>
</select>
</div>
</div>
JS:
var toggleFormSections = function(frameContent, sectionNumbers, enable) {
// init empty selector
var sections = $();
// collect sections
for(var i = 0; i < sectionNumbers.length; i++) {
var section = frameContent.find('div#section' + sectionNumbers[i]);
sections = sections.add(section);
}
// disable/enable sections and elements within
if(sections.length > 0) {
if(enable) {
sections.find('select').prop('disabled', false);
} else {
sections.find('select').prop('disabled', 'disabled');
}
}
}
// usage:
var frameContent = $('#frameContent');
toggleFormSections(frameContent, [2,3], false);
链接FIDDLE
这几乎是完美的:)如果sectionNumbers是单数,而不是一个数组?我正在使用启用标志来启用默认禁用的一些(不是全部)先前禁用的部分或部分。 – DeadMoroz
这只适用于一组数字(或一个空数组)。你可以添加一个检查到变量,看看它是否是一个数组。 – DrColossos