【发布时间】:2016-02-23 18:30:44
【问题描述】:
下面的代码大部分都有效。问题是,如果我从右框中删除一个项目并添加到左框中(反之亦然),那么列表不会按字母顺序排序。
我尝试了sort() 函数。例如,self.catagories.sort(),但它不起作用。它总是在最后添加项目。我需要有关此解决方案的帮助。
var categoryModel = function(category) {
this.category = ko.observable(category);
};
var viewModel=function(){
var self=this;
self.categories=ko.observableArray([new categoryModel("Hello"),new categoryModel("DHFDSHADS"),new categoryModel("yo"),new categoryModel("jai")]);
self.selectedCategory=ko.observableArray();
$('#add').click(function() {
var x= $('#select1 option:selected');
if(x.length>0){
x.each(function(){
alert($(this).text());
self.selectedCategory.push(new categoryModel($(this).text()));
$('#select1 option:selected').remove();
});
}
});
$('#remove').click(function() {
var x= $('#select2 option:selected');
if(x.length>0){
x.each(function(){
alert($(this).text());
self.categories.push(new categoryModel($(this).text()));
$('#select2 option:selected').remove();
});
}
});
};
$(document).ready(function() {
ko.applyBindings(new viewModel());
});
.liveExample select[multiple] { width: 20%; height: 8em; }
.liveExample h2 { margin-top: 0.4em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script>
<div class='liveExample'>
<p>Your items:</p>
<select multiple="multiple" id ="select1" width="5" data-bind="options: categories,optionsText:'category'"> </select>
<span>
<a href="#" id="add"> >> </a>
<a href="#" id="remove"> << </a>
</span>
<select multiple="multiple" id ="select2" width="5" data-bind="options: selectedCategory,optionsText:'category'"> </select>
</div>
【问题讨论】:
标签: jquery knockout.js