1

おはようございます。番号付きのセクションに分割されたフォームがあります。セクション番号を使用して、これらのセクションの一部を無効にする必要がある場合があります。関数がセクション番号の配列を受け取ると、ループを実行してそれらを 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);

フィドルへのリンク

4

2 に答える 2

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');
  }
});
于 2013-07-29T08:39:22.943 に答える
0

1つの方法は

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 に答える