简体   繁体   中英

HTML li element will not except

I am going through this signalR example at: https://docs.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-3.1&tabs=visual-studio .

Everything works where the Send button sends the user and the message to the server side signalR chat Hub. Then the Hub sends the user and message back to all the clients "ReceiveMessage" function callback on the Hub connection object in the Javascript. I have a bunch of console.log statements showing the user and message made it up to the server and back.

But there is this encoded message variable that you assign to an li element which gets added back to a element in the DOM.

But in the Javascript if I try to assign the encodedMsg to the li execution just stops. If I assign the static value 'Hello' it continues exection and works.

This is the signalR "ReceiveMessages" callback:

connection.on("ReceiveMessage", function (user, message) {
console.log("In client side: ReceiveMessage");
console.log(`user: ${user}`);
console.log(`message: ${message}`);
var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
console.log(`msg: ${msg}`);
var encodeMsg = user + " says " + msg;
console.log(`encodeMsg: ${encodeMsg}`);
var li = document.createElement("li");
console.log(`li: ${li}`);
li.textContent = 'Hello'; //encodedMsg;
console.log(`li.textContent: ${li.textContent}`);
document.getElementById("messagesList").appendChild(li);
});

Here the li.textContent gets a value:

在此处输入图片说明

But if I try to add the actual encodedMsg it seems to just stop execution:

connection.on("ReceiveMessage", function (user, message) {
    console.log("In client side: ReceiveMessage");
    console.log(`user: ${user}`);
    console.log(`message: ${message}`);
    var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    console.log(`msg: ${msg}`);
    var encodeMsg = user + " says " + msg;
    console.log(`encodeMsg: ${encodeMsg}`);
    var li = document.createElement("li");
    console.log(`li: ${li}`);
    /*li.textContent = 'Hello'; //encodedMsg; */
    li.textContent = encodedMsg;
    console.log(`li.textContent: ${li.textContent}`);
    document.getElementById("messagesList").appendChild(li);
    });

在此处输入图片说明

I am not great at JavaScript. Does anyone see why it does't want to assign the dynamic encodedMsg var to the li textContent?

You have a typo. You defined your variable as encodeMsg (note missing d ) but you are using it as encodedMsg

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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