繁体   English   中英

根据父选择元素的id属性更改选择选项的值

[英]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元素的值。

根据您的评论,如果idselect元素上,则显示为您想要的样子:

这里的例子

$('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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM