gpt4 book ai didi

javascript - Knockout.js:如何获取当前表单?

转载 作者:行者123 更新时间:2023-11-27 23:51:08 25 4
gpt4 key购买 nike

我是 KnockoutJS 的新手,我想序列化当前表单,但是当我 console.log 序列化表单时,它是空的。

如何引用当前表单?

这是我的 DOM:

<form data-bind="submit: onSubmit">
<input type="text" data-bind="value: firstName">
<input type="text" data-bind="value: lastName">
<button data-bind="click: capitalizeLastName">Go caps</button>
<input type="submit" value="submit">
</form>

这里是 JS 代码:

$(document).ready(function () {
function AppViewModel() {
var self = this;
self.firstName = ko.observable("Bert");
self.lastName = ko.observable("Bertington");
self.fullName = ko.computed(function() {
return self.firstName() + " " + self.lastName();
}, self);
self.capitalizeLastName = function() {
var currentVal = self.lastName(); // Read the current value
self.lastName(currentVal.toUpperCase()); // Write back a modified value
};

self.onSubmit = function(form) {
// alert( self.firstName()) ;
console.log($(form).serialize()) ;
}
}

// Activates knockout.js
ko.applyBindings(new AppViewModel());
});

最佳答案

您正确地引用了代码中的当前表单:它作为第一个参数传递给 submit然而,数据绑定(bind)处理程序仅 inputname属性由 jQuery.serialize() 序列化方法。添加name属性到您的字段,它将起作用。

来自https://api.jquery.com/serialize/ (粗体是我的)

Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.

但是,我建议您遵循评论中的 @James Thorpe 建议,并从 Knockout.js observables 中获取表单值。

关于javascript - Knockout.js:如何获取当前表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32697034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com