按元素名称中的索引选择元素
Select elements by index in elements name
早上好。我有一张表格,它被分成几个编号的部分。有时我需要使用它们的节号来禁用其中一些节。现在,当函数接收到一个节号数组时,我会运行一个循环来逐个收集它们。有没有一种更好、更有效的方法可以通过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');
}
});
一种方法是
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
相关文章:
- 如何索引jquery中的每个元素
- JavaScript DOM:在容器中查找元素索引
- 通过javascript中的元素索引访问eventListener中的元素
- 将页面元素索引到 JSON 对象?或者jQuery选择器它每次
- jQuery将相同的类添加到两个不同容器中的同一元素索引中
- 获取小元素索引直到数组长度
- jQuery获取元素索引,尽管包装器/父元素
- 更改数组中某些元素(索引)的顺序
- 访问具有公共类名的元素数组中的元素索引
- 访问循环的内部的ES6数组元素索引
- 列表类元素(索引).渐变(某些速度)不起作用
- javascript中的表单元素索引,用于jquery.change函数
- 获取文本块中的元素索引
- 用主干JS .get模型事件连接元素索引
- 从81个元素索引的数组中获取行和列值
- 如何使用javascript获得元素索引
- 使用类和子类获取元素索引
- Mootools从父元素获取子元素索引
- 如何在Javascript中获得一组固定元素的元素索引
- 使用jQuery更改列表元素索引