![](/img/trans.png)
[英]Dynamic multiple forms: Change select options based on previous select value
[英]Change the value of select options based on the id attribute of the parent select element
我有多个选择选项。 如果我选择一个特定的select
元素,例如id="a"
我想将option
值设置为0
。
$('#form option:selected').each(function() {
var id = $(this).attr('id');
if(id == 'a') {
val = 0;
} else {
val = 10;
}
console.log(val);
});
我得到了undefined
价值。
jQuery无法使用的部分原因是因为val
是一个undefined
变量。 您应该一直使用this.value
来设置/获取option
元素的值。
根据您的评论,如果id
在select
元素上,则显示为您想要的样子:
$('form option:selected').each(function() {
var id = $(this).parent().prop('id');
this.value = id === 'a' ? 0 : 10;
});
值得一提的是,只需使用.val()
方法即可简化代码。 它将遍历元素,您需要做的就是返回一个值:
$('form option:selected').val(function () {
return $(this).parent().prop('id') === 'a' ? 0 : 10;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.