简体   繁体   English

如何使用 Knockout 在父 div 之间动态移动子 div?

[英]How can I dynamically move child div between parent divs using Knockout?

In my sample, I have three parent divs (colored red) ... First, Second and Third.在我的示例中,我有三个父 div(红色)......第一个、第二个和第三个。

Initially I want to put my child div (colored yellow) in the "Second" div.最初,我想将我的孩子 div(黄色)放在“第二个”div 中。

After this, I want to move the child div between parent divs just by changing columnID.在此之后,我想通过更改 columnID 在父 div 之间移动子 div。

Here's my test code that does not work...这是我的测试代码不起作用...

 var dataColumns = [{ id: 1, text: "First" }, { id: 2, text: "Second" }, { id: 3, text: "Third" } ] var viewModel = { data: ko.observableArray([]), columns: ko.observableArray([]), }; dataColumns.forEach(function(c) { let column = { id: c.id, text: c.text, items: ko.computed(function() { return ko.utils.arrayFilter(viewModel.data(), function(d) { return d.columnID() === c.id; }); }, this) }; viewModel.columns.push(column); }); ko.applyBindings(viewModel); let item = { columnID: ko.observable(2), caption: "I am the moving item" }; viewModel.data.push(item); function MoveTo(index) { item.columnID(index); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <div data-bind="template: { name: 'columnTemplate', foreach: columns, as: 'column' }"></div> <script type="text/html" id="columnTemplate"> <div style="background-color: red;"> <div data-bind="text: text"></div> <div data-bind="template: { name: 'itemTemplate', foreach: column.items, as: 'item' }"></div> </div> </script> <script type="text/html" id="itemTemplate"> <div style="background-color: yellow;"> <div data-bind="text: caption"></div> </div> </script> <button onclick="MoveTo(1)">Move to column 1</button> <button onclick="MoveTo(2)">Move to column 2</button> <button onclick="MoveTo(3)">Move to column 3</button>

Fiddle: https://jsfiddle.net/MojoDK/at8grkwe/3/小提琴: https : //jsfiddle.net/MojoDK/at8grkwe/3/

Is my goal impossible to do with Knockuot?我的目标不可能用 Knockuot 实现吗?

My reallife project is a kanban system, where the id of the task specify which kanban column the task should be in - and then just by changeing then tasks columnID, the task should be moved to another kanban column.我的现实项目是一个看板系统,其中任务的 id 指定任务应该在哪个看板列中 - 然后只需更改任务列 ID,任务应该移动到另一个看板列。

UPDATE: I updated snippet and Fiddle to correct the error HeyJude pointed out - but it still doesn't move between columns when clicking the buttons.更新:我更新了代码段和 Fiddle 以更正 HeyJude 指出的错误 - 但单击按钮时它仍然不会在列之间移动。

It's only a small mistake you've got there.你在那里犯了一个小错误。

Change this:改变这个:

viewModel.columns.push(c);

... into this: ...进入这个:

viewModel.columns.push(column);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM