我有這個select
:設置默認值,如果沒有值
<select data-bind="options: $root.users(), optionsText: 'name', optionsValue: 'id', value: $root.selectedUser, optionsCaption: 'Select one'"></select>
我只需要如果$root.selectedUser = 0
否則我不需要的默認值要選擇的默認值(「選擇一個」)。
我試過:
<select data-bind="options: $root.users(), optionsText: 'name', optionsValue: 'id', value: $root.selectedUser, optionsCaption: $root.selectedUser() === 0 ? 'Select one' : ''"></select>
但它不工作。 (如果$root.selectedUser = 0
它顯示列表的第一個值而不是默認值。)
有關如何實現該目標的任何想法?
我無法重現您的錯誤:http://jsfiddle.net/ogLpxc0L/1/。你能更新小提琴嗎? –
@JoseLuis謝謝,我發現是什麼原因導致了這個問題:'selectedUser'無法獲得'0'值,當我將它設置爲'0'值時,它會得到'undefined'。爲什麼'selectedUser'不能是'0'?我添加了一個'console.log()到小提琴。 – user3378165
在小提琴的更新(http://jsfiddle.net/ogLpxc0L/4/)中,您可以選擇'0'。我添加了一行「Selected」,以顯示所選的實際值。另外,我將第一個用戶更改爲id = 0。在此鏈接(http://knockoutjs.com/documentation/options-binding.html)中,它表示「未定義」值顯示默認選項。 –