我有 3 个 HTML 组合/下拉框。它们都有不同的名称和标识。在特定事件上,我想获得所有三个的价值。任何人都可以给我一个代码片段吗?
问问题
5359 次
4 回答
5
使用 jQuery:
$("#dropdownID").val();
于 2009-09-23T08:44:24.837 回答
1
要做到这一点不使用 jQuery:
function getSelectValues() {
var values = [];
for (var i = 0; i < arguments.length; i++) {
var select = document.getElementById(arguments[i]);
if (select) {
values[i] = select.options[select.selectedIndex].value;
} else {
values[i] = null;
}
}
return values;
}
此函数返回一个值数组,这些值对应于id
您传递给函数的 s,如下所示:
var selectValues = getSelectValues('id1', 'id2', 'id3');
如果<select>
具有您指定id
的 s 之一的 a 不存在,则数组包含null
该位置的值。
还有其他几种方法可以做到这一点,您可以向函数传递一个id
值数组:getSelectValues([ 'id1', 'id2', 'id3' ])
,在这种情况下,函数将被更改:
function getSelectValues(ids) {
var values = [];
for (var i = 0; i < ids.length; i++) {
// ...
您还可以向函数传递id
s 的映射并填充值:
var myMap = { 'id1': null, 'id2': null, 'id3': null };
getSelectValues(myMap);
// myMap['id1'] contains the value for id1, etc
这会将函数更改为:
function getSelectValues(map) {
for (var id in map) {
var select = document.getElementById(id);
if (select) {
map[id] = select.options[select.selectedIndex].value;
} else {
map[id] = null;
}
}
}
于 2009-09-30T15:51:11.133 回答
1
我会尝试在您的 HTML 中将它们彼此相邻设置,然后使用 jQuery 的内置 each() 方法遍历它们。你会像这样设置你的元素:
<div id="dropdownBoxes">
<select id="firstElement">
<option>cool</option>
<option>neat</option>
</select>
<select id="secondElement">
<option>fun</option>
<option>awesome</option>
</select>
<select id="thirdElement">
<option>great</option>
<option>synonym</option>
</select>
</div>
<input type="button" id="theTrigger">Push me!</input>
然后,在您的脚本中:
var dropdownValues;
$("#theTrigger").click(function(){
dropdownValues.length=0;
$("#dropdownBoxes select").each(function(){
dropdownValues.push($(this).val());
});
});
于 2010-05-17T07:29:54.043 回答
0
使用像上面提到的 jQuery 这样的框架,或者只是按照老派的方式来做。document.getElementById('dropdownId').value
.
于 2009-09-30T15:47:04.243 回答