如何使用敲除选项绑定从select中删除值?

时间:2013-11-28 15:18:54

标签: javascript jquery knockout.js

我正在使用knockout来创建一个存储数组的表,我有一个创建的选项列表并放入一个可观察的数组中。我希望能够将年份添加到表中,但是从选择列表中删除了使用的值。目前我没有问题添加到表中的值,但我似乎无法从选择列表中删除值。这是我创建的fiddle

var yearList = function(){  
    var years = [];
    var id = 0; 
    for(var y=1950; y < 2056; y++) {
        id++;
        years.push({
            id:id
            ,year:y
        });
     }
    return years;
 }

var ViewModel = function() {
    var self = this;
    self.years = ko.observableArray(yearList());
    self.selectedYear = {};
    self.yearTable = ko.observableArray([
    {
        id:1
        ,year:2013
    },{
        id:2
        ,year:2014
    }
    ]);

    self.addYear = function() {
        var addEntry = self.selectedYear;
        self.yearTable.push(addEntry);
        $( "#dialog" ).dialog( "close" );
    }
};

ko.applyBindings(new ViewModel()); 

 $(function() {
    $( "#dialog" ).dialog({
      autoOpen: false,
      show: {
        effect: "blind",
        duration: 1000
      },
      hide: {
        effect: "explode",
        duration: 1000
      }
    });

    $( document ).on('click','#newEntry',function() {
      $( "#dialog" ).dialog( "open" );
    });
});

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

使用remove方法http://knockoutjs.com/documentation/observableArrays.html http://jsfiddle.net/tarabyte/JTJ8n/12/

self.addYear = function() {
        var addEntry = self.selectedYear;
        self.yearTable.push(addEntry);
        self.years.remove(addEntry); //tada!
        $( "#dialog" ).dialog( "close" );
    }

答案 1 :(得分:1)

您只需要在.remove阵列上调用self.years方法。

请参阅此处的小提琴:http://jsfiddle.net/JTJ8n/13/

<强>段:

self.addYear = function() {
    var addEntry = self.selectedYear;
    self.yearTable.push(addEntry);
    self.years.remove(addEntry);
    $( "#dialog" ).dialog( "close" );
}