如何将这个冗长的jQuery变得优雅?

时间:2015-08-06 22:37:22

标签: 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和args函数。我,我还需要

$(document).on("change", '[id$=ddlPaymentType2]', function () {
    . . .
});

......等(通过ddlPaymentType5)。

有什么更好的方法来实现这一目标?

3 个答案:

答案 0 :(得分:2)

你可以这样做:

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

答案 1 :(得分:1)

这就是你要找的......?

 $(document).on("change", '[id$=ddlPaymentType1]', function () {
      var value = $(this).val();        
        $('[id$=ddlAccount1]').text("Replace this with the values for selection " + value);                   
        /* TODO: Add the rest (not value=11, as that is the "VENDORS" category item (not a real selection in itself)) */
    });

答案 2 :(得分:0)

在上面的Jan的帮助下(如本页上面的答案,而不是居住在天堂的人)和jQuery论坛上的“jakecigar”,以及我自己的“加回”( var options =选择[$(this).val()];)其遗漏导致错误,这就是我现在用作起点:

$(document).on("change", '[id$=ddlPaymentType1]', function () {
    var selects = [
    [
        ["value 1", "text 1"],
        ["value 2", "text 2"]
    ],
    [
        ["value 1", "text 1"],
        ["value 2", "text 2"]
    ]
    /* Rest of your values here */
  ]

  var $select = $('[id$=ddlAccount1]');
  $select.empty();

  var options = selects[$(this).val()];

  console.log(options, $select)

  $.each(options, function (i, item) {
  console.log(item)
  $select.append($("<option />", {
      value: item[0],
      text: item[1]
    }))
  });        
});