javascript - 如何让这个冗长的 jQuery 变得优雅呢?

标签 javascript jquery

我有 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]));
});

http://jsbin.com/wukovavupe/edit?html,js,output

关于javascript - 如何让这个冗长的 jQuery 变得优雅呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31866917/

相关文章:

javascript - Three.js 中 Material 的漫反射贴图和颜色之间的相关性

javascript - 如何在react功能组件中绑定(bind)? .bind(this) 不起作用

javascript - 无法使用ajax添加评论

悬停时 JQuery Center 溢出 DIV

javascript - 根据输入的字符动态增加输入类型文本文本框的宽度

Javascript 函数警报在 Visual Studio 模拟器中未定义

jquery - 是否可以调整粘在左侧的 div 的宽度以始终覆盖始终居中的 div?

javascript - 如何使用 jquery ajax 从 mvc Controller 获取 <list> 进行查看

jQuery 1.8 外部高度/宽度不起作用

javascript - 如何使变量成为全局变量以满足需求