1

Good morning. I have a form that is divided into numbered sections. Sometimes I need to disable some of these sections by using their section numbers. Right now when the function receives an array of section numbers I run a loop to collect them one-by-one. Is there a better, more efficient way of collecting numbered sections by their section numbers with 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);

Link to FIDDLE

4

2 回答 2

2

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

您可以轻松地使用 jQueryeach循环遍历索引元素,无需检查它的长度。我不太确定,你为什么要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');
  }
});
于 2013-07-29T08:39:22.943 回答
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);
}

演示:小提琴

于 2013-07-29T08:40:12.523 回答