1

Im using knockout and i want to insert / show a div between 2 divs. Basically im creating an employee details page. The employees will be listed and when a user clicks on the employee i want his / her details to show under the employee

<div>user 1</div>
<div>user 2</div>
<div>user 3</div>

clicked

<div>user 1</div>
<div>User Details etc</div>
<div>user 2</div>
<div>user 3</div>

Im storing the selected user in an editable property which is populated when an employee is clicked and using a with binding i can get the user to come up after all the users, but i would really like to get the details to come up under the relevant employee. Any ideas?

Heres a link to quick fiddle ive done

4

1 回答 1

5

KnockoutJS 不会以这种方式操作 DOM。您可以使用 jquery 或本机 js document.createElement('User Details etc') 并将其附加在用户 div 之间。在淘汰赛中最接近这种行为的是IF绑定。最后解释了。还是要先定义在那里,然后淘汰赛才能控制。

对于淘汰赛方式,您可以从可见性开始:

<div>user 1</div>
<div data-bind="visible: selectedUser() == user1">User 1 Details etc</div>
<div>user 2</div>
<div data-bind="visible: selectedUser() == user2">User 2 Details etc</div>
<div>user 3</div>
<div data-bind="visible: selectedUser() == user3">User 3 Details etc</div>

或者更好的是,在循环中:

<!-- ko foreach: users -->
    <div data-bind="text: $data.userName"></div>
    <div data-bind="visible: $parent.selectedUser() == $data.userName, text: $data.userDetails"></div>
<!-- /ko -->

如果您想将这些 div 保留在 DOM 之外,请更改visibilityif. 来自淘汰网站:

if 与可见绑定的作用相似。不同之处在于,对于可见,包含的标记始终保留在 DOM 中,并且始终应用其数据绑定属性 - 可见绑定仅使用 CSS 来切换容器元素的可见性。然而,if 绑定在物理上添加或删除 DOM 中包含的标记,并且仅在表达式为真时才将绑定应用于后代。

您可以在文档中阅读更多内容:http: //knockoutjs.com/documentation/if-binding.html

编辑:和你修改过的 JSfiddle:http: //jsfiddle.net/XwcK9/1/

于 2013-07-25T10:33:02.490 回答