[英]Retrieving value from select list with knockout.js
我正在使用Knockout.js 2.3.0,並且試圖檢索選擇列表中設置的值,但是我無法使其正常工作。 當我嘗試提醒該值時,我會看到javascript,未定義或[對象對象](取決於我嘗試過的內容)。
該列表已填充好,我可以設置默認值,但無法檢索它。 我究竟做錯了什么?
這是列表的HTML
<select data-bind='value: selectedMonth, options: $root.months, optionsText: "month"'></select>
這是JS
self.months = [{month: '-'},{month: '01'},{month: '02'},{month: '03'},{month: '04'},{month: '05'},{month: '06'},{month: '07'},{month: '08'},{month: '09'},{month: '10'},{month: '11'},{month: '12'}];
self.selectedMonth = ko.observable(self.months[0]);
self.submitButton = function(){
alert(self.selectedMonth); //a bunch of JavaScript
alert(self.selectedMonth()); //object, Object
alert(self.months[self.selectedMonth]); //undefined
}
您的第二個電話是您想要的電話:
self.selectedMonth()
這將可觀察值解包為該值。 它是一個對象,例如:
{ month: "03" }
如果使用console.log
而不是alert
console.log
容易發現 。
無論如何,要獲取月份值,只需請求該屬性即可:
alert(self.selectedMonth().month);
看到這個小提琴 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.