我想使用knockout在控制台中打印输入元素的值。
当我尝试打印该值时,我得到“结果”而不是文本框的值。
var ViewModel = {
name: ko.observable("name"),
company: ko.observable("company"),
submit: ko.observable("Submit"),
onsubmit: function(){
console.log(name);
}
}
ko.applyBindings(ViewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<form>
<label>Name</label>
<input type="text" data-bind="value:name"/>
<label>Company</label>
<input type="text" data-bind="value:company"/>
<button data-bind="click:onsubmit,text:submit"></button>
</form>
答案 0 :(得分:1)
您也可以这样做。我想为我的viewmodel声明一个函数,以便以后可以用来初始化另一个新对象。
var ViewModel = function() {
var self = this;
self.name = ko.observable("name");
self.company = ko.observable("company");
self.submit = ko.observable("Submit");
self.onsubmit = function(){
alert(self.name())
console.log(self.name());
};
}
ko.applyBindings(new ViewModel());
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<label>Name</label>
<input type="text" data-bind="value: name"/>
<label>Company</label>
<input type="text" data-bind="value: company"/>
<button data-bind="click: onsubmit, text: submit"></button>
&#13;