按元素名称中的索引选择元素

时间:2013-07-29 08:31:51

标签: javascript jquery select

早上好。我有一个分为编号部分的表格。有时我需要使用它们的节号来禁用其中一些节。现在,当函数接收到一个段号数组时,我会运行一个循环来逐个收集它们。是否有更好,更有效的方法通过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 个答案:

答案 0 :(得分: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');
  }
});

答案 1 :(得分: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

相关问题