How to use ternary operator in JavaScript?

时间:2016-02-03 03:44:57

标签: javascript jquery

My case is like this:

...
success:function(data) {
    jQuery.each(data.SearchCityResponse.Nation.City, function(key,value) {
        console.log(value.CityCode);
        city.append(jQuery("<option value.CityCod==\'CEB\')?\'selected\':\'\'></option>").val(value.CityCode).text(value.CityName));
    });
    city.select2();
}
...

I check in console: http://imgur.com/jIO8nYk

This seems like a problem writing ternary

1 个答案:

答案 0 :(得分:2)

"<option value.CityCod==\'CEB\')?\'selected\':\'\'></option>" is just a string and it'll not parse any variable or the JavaScript operator.

Also, there is typo, CityCod should be CityCode.

You can use concatenation + operator

"<option " + (value.CityCode === 'CEB' ? 'selected' : '') + "></option>"

Or, the selected status can be kept in a variable and that variable can be used.

var selected = value.CityCode === 'CEB' ? 'selected' : '';
"<option " + selected + "></option>"

You can also use the prop() to set the selected status.

$("<option />")
    .val(value.CityCode).text(value.CityName)
    .prop('selected', value.CityCode === 'CEB');