我有 5 行,每行的第一个单元格中都有相同的选择元素(或 dropDownList)。从中选择一个值来填充另一个选择元素中的值。
如何填充选择项,并且采用比此处的“强力”方法更简洁的方式:
$(document).on("change", '[id$=ddlPaymentType1]', function () {
var value = $(this).val();
if (value == '1') {
$('[id$=ddlAccount1]').text("Replace this with the values for selection 1");
}
else if (value == '2') {{
$('[id$=ddlAccount1]').text("Replace this with the values for selection 2");
}
else if (value == '3') {{
$('[id$=ddlAccount1]').text("Replace this with the values for selection 3");
}
else if (value == '4') {{
$('[id$=ddlAccount1]').text("Replace this with the values for selection 4");
}
else if (value == '5') {{
$('[id$=ddlAccount1]').text("Replace this with the values for selection 5");
}
else if (value == '6') {{
$('[id$=ddlAccount1]').text("Replace this with the values for selection 6");
}
/* TODO: Add the rest (not value=11, as that is the "VENDORS" category item (not a real selection in itself)) */
});
通过上述内容,我将必须响应大约 20 个不同的值(仅显示 6 个),并且我将必须响应 5 个相同的(除了 ID 和参数之外)函数。 IOW,我还需要
$(document).on("change", '[id$=ddlPaymentType2]', function () {
. . .
});
...等(直到 ddlPaymentType5)。
什么是更好的方法来实现这一目标?
最佳答案
例如,您可以这样做:
var selects = { "1": [
["value 1", "text 1"],
["value 2", "text 2"]
]
,"2": [
["value 1", "text 1"],
["value 2", "text 2"]
]
, /* Rest of your values here */
};
var $select = $('[id$=ddlAccount1]');
$select.children().remove();
var options = selects[$(this).val()];
options.forEach(function(item) {
$select.append($("<option />").val(item[0]).text(item[1]));
});
关于javascript - 如何让这个冗长的 jQuery 变得优雅呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31866917/