我如何在html div中存储字符串值?

问题描述 投票:0回答:4

我正在尝试为我的学校项目制作一个简单的Messenger

我需要在自己内部存储每个聊天消息的ID号(这是一个div标签),我想使用ID或div名称从JavaScript访问此值。

对不起我的英语不好

javascript html
4个回答
1
投票

您可以在自定义属性中存储任意数据。

<div id="id1" any="value">

document.getElementById("id1").getAttribute("any");

4
投票

假设div标签的ID等于NumberID(<div id="NumberID"></div>]

如果您想使用javascript,

var NumberID = document.getElementById("NumberID").innerHTML;

然后您可以从NumberID变量中获取结果。


0
投票
divID = 'the id of your div';
content = 'the content you want in that div';
div = document.getElementById(divID);
div.innerHTML(content);

文档:

.getElementByID

.innerHTML


0
投票

所以您要用于存储的是一个数组,因为它比DOM快得多,而DOM不是您的存储。这里是一个小代码示例,如何使用数组存储内容,提取和foreach

// declaring the array
const messages = [];

// can be automated to restructure incoming dataformat
function incoming(nodeId, msgId, msg) {
    messages.push({
        // you can store the html node directly for faster access
        // even better if you pass the node as a parameter
        // "node": document.getElementById(nodeId),
        "node": nodeId,
        "msgId": msgId,
        "msg": msg
    })
    // do other stuff here example:
    // appendMsg();
}

// incoming messages
incoming("box-1", 25823, "hi, whats up??")
incoming("box-2", 25824, "not much...")
incoming("box-3", 25825, "wanna learn JS?")
let searchResult = messages.find((ele) => {
    // use return ele.node.id == `box-1` if you store the elements and want to find an element
    return ele.node == "box-2"  
})
console.log(searchResult)

// using map to print the text of all messages
messages.map(ele => console.log(ele.msg))
© www.soinside.com 2019 - 2024. All rights reserved.