淘汰赛 JS 数组为空或无法检索值? [英] Knockout JS array empty or can't retrieve values?

查看:23
本文介绍了淘汰赛 JS 数组为空或无法检索值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Javascript ajax 函数,可以从服务器检索评论(注意:我是 Knockout JS 的新手):

function Comments() {var self = this;self.commentArray = ko.observableArray();self.getNewerComments = 函数(lastCommentId){pageId = $('body').attr('id');$.ajax({类型:获取",数据类型:json",url: "Controller/getNewerComments/" + pageId + "/" + lastCommentId,}).完成(功能(数据){self.commentArray = ko.observableArray(data);警报(self.commentArray[0].authorName);})}}

通过警报,我可以看到该值确实设置在那里,在我的 JS 文件的开头,我有以下代码:

var comments = new Comments();ko.applyBindings(评论);评论.getNewerComments(0);

在 html 文件中:

<li>Item <span data-bind="text: $index"></span></li><!--/ko -->

然而,html 文档中没有显示任何内容,甚至没有显示项目"文本,这表明数组长度为 0.这里有什么问题?为什么我不能使用数组值?

谢谢.

解决方案

您应该使用现有的 observable 数组(已绑定)而不是创建一个新数组:

.done(function(data) {self.commentArray(data);警报(self.commentArray[0].authorName);})

I have a Javascript ajax function that retrieves comments from the server(Note: I'm new to Knockout JS):

function Comments() {
var self = this;
self.commentArray = ko.observableArray();
self.getNewerComments = function(lastCommentId) {
    pageId = $('body').attr('id');
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "Controller/getNewerComments/" + pageId + "/" + lastCommentId,


    })
            .done(function(data) {

                self.commentArray = ko.observableArray(data);
                alert(self.commentArray[0].authorName);


            })

}

}

With the alert I can see that the value is indeed set there, at the start of my JS file I have the following code:

var comments = new Comments();
ko.applyBindings(comments);
comments.getNewerComments(0);

And in the html file:

<!-- ko foreach: commentArray -->
<li>Item <span data-bind="text: $index"></span></li>
<!-- /ko -->
</div>

However, nothing shows up in the html document, not even the "Item" text, which indicates the array has 0 length. What's the problem here? Why can't I use the array values?

Thank you.

解决方案

You should use existing observable array (which was bound) instead of creating a new one:

.done(function(data) {
   self.commentArray(data);
   alert(self.commentArray[0].authorName);
 })

这篇关于淘汰赛 JS 数组为空或无法检索值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆