gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:56:59 25 4
gpt4 key购买 nike

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

最佳答案

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');
}
});

关于javascript - 按元素名称中的索引选择元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17919329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com