这是我的代码:
$.each(cities.cities, function (i, item) {
$('select#city').append($('<option>', {
value: item.id,
text : item.name
}));
});
现在我需要在追加方式上添加一个条件。我的意思是我想将selected
属性添加到与item.id
变量city_id
相同的选项中。我怎么能这样做?
答案 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>