gpt4 book ai didi

javascript - knockout JS : adding forms in foreach bindings

转载 作者:行者123 更新时间:2023-12-01 01:26:06 25 4
gpt4 key购买 nike

我想添加一个“删除评论”按钮作为表单,该按钮会在使用 knockout 的 foreach 绑定(bind)生成的每个评论旁边触发 ajax 请求。 comments是一个可观察数组,每条评论都是一个 username 的对象, text , timestampcommentID成员。加载以下内容而不使用 <form>元素工作正常:

<ul data-bind="foreach: comments">
<li>
<span data-bind="text: username"></span>
<ul>
<li data-bind="text: text"></li>
<li data-bind="text: timestamp"></li>
<form data-bind="if: sameUser" method="post" action="deleteComment.php">
<input data-bind="attr: {id: commentID}, click: deleteComment" type="submit" value="Delete comment">
</form>
</ul>
</li>
</ul>

但是,包括 <form>元素打破了 foreach 循环,仅加载一条注释。

我想使用if: sameUser数据绑定(bind),以便删除按钮仅对发布评论的用户可见,并且 attr: {id: commentID} data-bind 在单击按钮时将要删除的正确评论 ID 发送到服务器,但现在我主要关心的是首先加载表单/按钮。

正确的方法是什么?

最佳答案

Not sure if you are writing delete function on comment level or its list level but if are binding the function use $parent to get out of foreach context.

以下是工作示例

function viewModel() {
var self = this;

self.comments = ko.observableArray([]);
self.isDataLoaded = ko.observable(false);

self.loadData = function(){
setTimeout(function(){
self.comments.push({username:"A", sameUser:true, commentID:1, text:"This is comment from A"});
self.comments.push({username:"B", sameUser:true, commentID:2, text:"This is comment from B"});
self.comments.push({username:"C", sameUser:false, commentID:3, text:"This is comment from C"});
self.comments.push({username:"D", sameUser:true, commentID:4, text:"This is comment from D"});
self.isDataLoaded(true);
}, 2000);
}
self.deleteComment = function(data){
self.comments.remove(data);
}
}

var vm = new viewModel();
vm.loadData();
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul data-bind="foreach: comments">
<li>
<span data-bind="text: username"></span>
<ul>
<li data-bind="text: text"></li>
<!--<li data-bind="text: timestamp"></li> -->
<form data-bind="if: sameUser" method="post">
<input data-bind="attr: {id: commentID}, click: $parent.deleteComment" type="submit" value="Delete comment">
</form>
</ul>
</li>
</ul>

关于javascript - knockout JS : adding forms in foreach bindings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53769934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com