Knockout绑定文本框以选择文本

时间:2016-09-30 19:21:12

标签: javascript knockout.js

最近我开始学习前端开发,所以如果这个问题太愚蠢,不要感到惊讶。 我想要做的是绑定文本框以选择文本,而不是它的id。这是一个jsfiddle:https://jsfiddle.net/1rtzfLr1/

这是我的HTML:

<div data-bind="foreach: objects()">
  <input type="text" data-bind="value: type" />  
  <button type="button" data-bind="click: $parent.removeObject">-</button>
</div>
<div>
  <select data-bind="options: types, optionsValue: 'id', optionsText: 'title', optionsCaption: 'Type...', value: itemToAdd().type"></select>  
  <button id="create-object-button" type="button" data-bind="click: addObject">+</button>
</div>

和JS:

function model() {
  var self = this;

  self.objects = ko.observableArray();
  self.types = ko.observableArray([new Type(1, 'one'), new Type(2, 'two'), new Type(3, 'three')]);
  self.itemToAdd = ko.observable(new Object());

  self.addObject = function() {
    self.objects.push(self.itemToAdd());
    self.itemToAdd(new Object());
  };

  self.removeObject = function(object) {
    self.objects.remove(object);
  };

  function Object(type) {
    var self = this;
    self.type = type;
  }

  function Type(id, title) {
    var self = this;
    self.id = id;
    self.title = title;
  }
};

ko.applyBindings(new model());

问题是我想在文本框中显示two而不是2,但同时这是应该提交的表单的一部分,并且在表单提交时我会喜欢在实际应用程序中提交2值,它是java enum name。

如果问题太乱,谢谢,对不起。

1 个答案:

答案 0 :(得分:0)

抱歉不是肯定你在追求什么,但也许是这样的? http://jsfiddle.net/LkqTU/31963/

JS

function type(id, title) {
  var self = this;
  self.id = ko.observable(id);
  self.title = ko.observable(title);
};

var initialArray = [
  new type(1, 'one'),
  new type(2, 'two'),
  new type(3, 'three')
]


function model() {
  var self = this;

  self.types = ko.observableArray(initialArray);
  self.options = ko.observableArray(initialArray);
  self.selectedtype = ko.observable('');
  self.removeObject = function(p) {
    self.types.remove(p);
  }
  self.addObject = function() {
    self.types.push(new type(
      self.selectedtype().id(),
      self.selectedtype().title()));
  }
}

var mymodel = new model();

$(document).ready(function() {
  ko.applyBindings(mymodel);
});

HTML

<div data-bind="foreach: types">
  <p>
    <span data-bind="text: id"></span>:
    <input type="text" data-bind="value: title" />
    <button data-bind="click: $parent.removeObject">
  </p>

  -
  </button>

</div>
<br/>
<select data-bind="options: options,
                       optionsText: 'title',
                       value: selectedtype,
                       optionsCaption: 'Choose...'"></select>
<button data-bind="click: addObject">+</button>

</button>