假设我有一个带有此html代码的jquery模板:
<div>
<span id="myfirstname"></span>
<select id="mygender" multiple="multiple">
<option value="1">-select-</option>
<option value="2">Male</option>
<option value="3">Female</option>
<option value="4">NotSpecified</option>
</select>
</div>
我的json看起来像是:{ "FirstName": "John", "Gender": "Male" };
我可以使用$ {FirstName}绑定myfirstname但是如何绑定下拉值?我使用了$ {Gender},但只显示了值而不是下拉列表,并选择了“男性”选项。
答案 0 :(得分:0)
一种选择是:
<div>
<span id="myfirstname">${FirstName}</span>
<select id="mygender" multiple="multiple">
<option value="1">-select-</option>
<option value="2" {{if Gender == 'Male'}}selected="selected"{{/if}}>Male</option>
<option value="3" {{if Gender == 'Female'}}selected="selected"{{/if}}>Female</option>
<option value="4" {{if Gender == 'NotSpecified'}}selected="selected"{{/if}}>NotSpecified</option>
</select>
</div>
如果这太冗长,那么你可以创建一个函数来进行匹配,如:
function match(value, choice) {
return value === choice ? "selected='selected'" : "";
}
然后做:
<div>
<span id="myfirstname">${FirstName}</span>
<select id="mygender" multiple="multiple">
<option value="1">-select-</option>
<option value="2" ${match(Gender, 'Male')}>Male</option>
<option value="3" ${match(Gender, 'Female')}>Female</option>
<option value="4" ${match(Gender, 'NotSpecified')}>NotSpecified</option>
</select>
</div>