2013-07-29 83 views
1

早上好。我有一个分为数字部分的表格。有时我需要通过使用它们的部分编号来禁用这些部分中的一部分。现在,当函数接收到一系列节号时,我会运行一个循环来逐一收集它们。有没有更好,更有效的方式来收集编号的部分与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

回答

2

http://jsfiddle.net/XZ9fT/3/

您可以轻松地使用jQuery的each遍历索引的元素,没有必要检查它的长度。我不太确定,为什么你想要enabled标志。既然你可以用一个空数组来调用它来启用一切。这会使它更短。

$.each(sectionNumbers, function(i) { 
    if(enable) { 
    frameContent.find('div#section' + sectionNumbers[i] + ' select').prop('disabled', false) 
    } else { 
    frameContent.find('div#section' + sectionNumbers[i] + ' select').prop('disabled', 'disabled'); 
    } 
}); 
+0

这几乎是完美的:)如果sectionNumbers是单数,而不是一个数组?我正在使用启用标志来启用默认禁用的一些(不是全部)先前禁用的部分或部分。 – DeadMoroz

+0

这只适用于一组数字(或一个空数组)。你可以添加一个检查到变量,看看它是否是一个数组。 – DrColossos

0

的方法之一将是

var toggleFormSections = function(frameContent, sectionNumbers, enable) { 
    // init empty selector 
    var sections = []; 

    // collect sections 
    for(var i = 0; i < sectionNumbers.length; i++) { 
     sections.push('#section' + sectionNumbers[i]); 
    } 
    sections = $(sections.join(', ')) 

    sections.find('select').prop('disabled', !enable); 
} 

演示:Fiddle