如何在.append()的路上添加条件?

时间:2017-12-11 12:38:59

标签: javascript jquery html

这是我的代码:

$.each(cities.cities, function (i, item) {
    $('select#city').append($('<option>', {
        value: item.id,
        text : item.name
    }));
});

现在我需要在追加方式上添加一个条件。我的意思是我想将selected属性添加到与item.id变量city_id相同的选项中。我怎么能这样做?

2 个答案:

答案 0 :(得分:3)

selected是布尔属性 - 可以是条件的结果:

$.each(cities.cities, function (i, item) {
    $('select#city').append($('<option>', {
        value: item.id,
        text : item.name,
        selected: item.id === city_id
    }));
});

答案 1 :(得分:1)

如果您的目标是仅在 selected评估为item.id === city_id时才设置true属性,则执行此操作的一种方法如下:

$.each(cities.cities, function (i, item) {
    /* Create a data object. */
    var data = {
       value: item.id,
       text : item.name,
    };

    /* Check whether the ids are equal. */
    if (item.id === city_id) data.selected = "";

    /* Use the data object to create the option and append it. */
    $('select#city').append($('<option>', data));
});

以上将产生:

<option value = "..." text = "..." selected/>

<强>段:

/* ----- JavaScript ----- */
var
  city_id = 2,
  cities = [
    {id: 1, name: "Amsterdam"},
    {id: 2, name: "Athens"},
    {id: 3, name: "Berlin"}
  ];

$.each(cities, function (i, item) {
  /* Create a data object. */
  var data = {
     value: item.id,
     text : item.name,
  };

  /* Check whether the ids are equal. */
  if (item.id === city_id) data.selected = "";

  /* Use the data object to create the option and append it. */
  $('select#city').append($('<option>', data));
  
  /* Log the created option. */
  console.log($('select#city').children().last()[0]);
});
<!---- HTML ----->
<script src = "//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id = "city"></select>