【发布时间】:2017-02-11 03:41:28
【问题描述】:
我很难理解这个问题。我正在使用 KnockoutJS,并且我有一个可观察的选择下拉菜单。当我更改该下拉列表的值时,我希望它在我的表中每行更改一个隐藏输入。我无法弄清楚如何在订阅函数中设置该值。我知道订阅函数被调用是因为我的控制台输出运行。
这是我的 HTML 选择和我想要更改的隐藏输入的部分表格:
<div data-bind="if: (availableProfitCodes().length > 1)">
<select id="profitCode" data-bind="value: selectedProfitCode, options: availableProfitCodes, optionsText: function(code) { return code.name + ' : ' + code.desc }, optionsValue: 'code', optionsCaption: '-- select a profit code --'"></select>
</div>
<tbody data-bind="foreach: codes">
<tr>
<td>
<input data-bind="value: itemNo, attr: { name: 'brochureProfitCodes[' + $index() + '].itemNo', id: 'brochureProfitCodes_' + $index() + '__itemNo' }, validationOptions: { errorElementClass: 'input-validation-error' }" class="form-control" readonly="readonly" tabindex="-1" />
<input data-bind="value: profitCode, attr: {name: 'brochureProfitCodes[' + $index() + '].profitCode', id: 'brochureProfitCodes_' + $index() + '__profitCode' }" type="hidden" class="profitCode" />
</td>
还有我的淘汰码(不工作的部分在订阅函数中):
var CodeModel = function(data) {
var self = this;
self.profitCode = ko.observable(data ? data.profitCode : '');
self.itemNo = data.itemNo;
self.brocCode = data.brocCode;
self.brochureID = data.brochureID;
self.itemDesc = data.itemDesc;
self.retail = data.retail;
self.wholesale = data.wholesale;
self.commission = data.commission;
}
var codesModel = function(codes) {
var self = this;
self.availableProfitCodes = ko.observableArray([]);
self.selectedProfitCode = ko.observable();
//self.codes = ko.observableArray(codes);
//self.codes = ko.observable(new CodeModel());
if(codes != null) {
self.codes = ko.observableArray(codes.map(function(code) { return new CodeModel(code) }));
}
self.selectedProfitCode.subscribe(function(newValue) {
console.log("newValue is: " + newValue);
self.codes.profitCode(newValue);
});
};
$(document).ready(function () {
var profitCodeInt = Number($.trim($("#pCode").val()));
if(profitCodeInt == 0) { // adding a new profit code
...
}
else if(profitCodeInt > 0) { // editing an existing profit code
$.ajax({
url: '@Url.Action("GetProfitCodesJSON", "Brochure")',
type: 'POST',
success: function(json) {
var codesJSON = @Html.Raw(Json.Encode(Model.brochureProfitCodes));
console.log(JSON.stringify(codesJSON));
var itemsJSON = @Html.Raw(Json.Encode(Model.brochureItems));
viewModel = new codesModel(codesJSON);
var result = json.profitCodes.filter(function( obj ) {
return obj.profitCode == profitCodeInt;
});
var code = new profitCode(result[0].profitCode, result[0].profitDesc, result[0].profitName);
viewModel.availableProfitCodes.push(code);
ko.applyBindings(viewModel, $("#profitModal")[0]);
}
});
【问题讨论】:
-
你有几个版本的codeModel.codes,所以我不确定你目前使用的是什么,但我认为codes应该是一个数组?如果是这样,您只需要遍历每个项目并设置项目的利润代码,而不是在集合本身上设置利润代码。 for(var x=0; x