尝试附加基本html时,Node.appendChild的参数1不是对象 [英] Argument 1 of Node.appendChild is not an object when trying to append basic html

查看:717
本文介绍了尝试附加基本html时,Node.appendChild的参数1不是对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般信息

我目前正在使用websocket处理聊天系统。除了消息之外,我使用相同的websocket向用户显示当前在线用户列表。

General Info
I'm currently working on a chatsystem using a websocket. Aside from the messages, I'm using the same websocket to present the user with a userlist of those currently online.

问题

几天以来,我一直在尝试使用OOP方法编写所有Javascript脚本。到目前为止,它已经相当不错,但现在我已经弄错了一个我真实不明白的错误:

The Problem
Since a couple of days I've been trying to script all of my Javascript purely in OOP approach. So far it's going pretty well but now I've stumpled upon a error I honestly don't understand:

Node.appendChild的参数1不是对象

代码

我尽可能缩小代码范围以仅代表重要部分:

The Code
I've narrowed down my code as far as possible to only represent the important parts:

var CB = CB || {};

CB.messages = {
    userListLayout: function(Username){
        var userListTable = "<table class='userTable' data-user='"+ Username +"'><tbody><tr><td><img src='layout/images/default_profile.png'></td><td>" + Username + "</td></tr></tbody></table>";

        return userListTable;
    }
}

CB.users = {
    set: function(Usernames) {
        var List = document.getElementById('usersList'); // Represents an empty div
        var i, j = Usernames.length, ListUser;

        for (i=0; i<j; i++) {
            ListUser = CB.messages.userListLayout(Usernames[i]);
            List.appendChild(ListUser); // Error
        }
    }
}

所以问题是:我做错了什么以及解决它的最佳方法是什么?

So the question is: What am I doing wrong and what's the best way to fix it?

推荐答案

ListUser 是一个HTML字符串。 Node.appendChild 只接受DOM节点作为参数。

ListUser is a string of HTML. Node.appendChild only accepts a DOM node as an argument.

https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild

这里有两个选项,要么在节点中包装所需的文本,要使用 appendChild 或保留当前设置并使用 innerHTML ,它允许您向HTML文档添加字符串:

You have two options here, either wrap the text you want in a node and use appendChild or keep the current setup and use innerHTML which allows you to add a string to the HTML document:

List.innerHTML + = ListUser

这篇关于尝试附加基本html时,Node.appendChild的参数1不是对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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