【问题标题】:Add value for DOM nodes in list为列表中的 DOM 节点添加值
【发布时间】:2020-05-20 19:23:56
【问题描述】:

我正在尝试使用数据库中的数据中的 DOM 节点创建链接列表。而不是每个 DOM 元素都有一个链接。整个列表只有一个链接。我希望链接是分开的,因为我想为它增加价值,这样我就可以识别用户点击了哪个链接。 这是 HTML 中的链接

    <a href="hearsong.html" id="songlist" value=""></a>

这是我从数据库中获取数据的 Javascript 代码。我想把每个对应的数据库作为HTML代码中对应链接的值。

window.onload = async function outsong() {
        var selected = localStorage.getItem("category")
        document.getElementById("result").innerHTML = selected;
        var result = [];
        if(selected == "Popular") {
            await db.collection("Song").doc("Popular").collection("songs").get().then(function(querySnapshot) {
                querySnapshot.forEach(function(doc) {
                    // doc.data() is never undefined for query doc snapshots
                    console.log(doc.id, " => ", doc.data());
                    result.push(doc.data());
                });
            });
            console.log(result.length);
            for(a = 0; a < result.length; a++) {
                var node = document.createElement("li");

                var textnode = document.createTextNode(result[a].song_name);
                node.appendChild(textnode);

                document.getElementById("songlist").appendChild(node);
                var anchor = document.getElementById("songlist");
                var att = document.createAttribute("value");
                att.value = result[a].song_name;
                anchor.setAttributeNode(att);
    }
}

在图片中,我想将链接分开,而不是一个整体。

【问题讨论】:

    标签: javascript html google-cloud-firestore


    【解决方案1】:

    在您的循环中,您需要在每个&lt;li&gt; 中创建一个新的&lt;a&gt; 元素,并将歌曲链接添加到该元素。修改代码:

    const songList = document.getElementById("songlist");
    
    for(let a = 0; a < result.length; a++) {
        var node = document.createElement("li");
        
        var link = document.createElement('a');
        link.setAttribute('href', result[a].song_link);
        link.innerText = result[a].song_name;
        
        node.appendChild(link);
        songList.appendChild(node);
    }

    我看不出你从哪里得到 song_link,所以为了这个例子,我猜它是在 result[a] 对象中,旁边是 song_name。

    【讨论】:

    • &lt;a&gt; 元素不采用 value 属性。
    • 谢谢。您的代码将问题作为一个整体解决了一个链接。我正在尝试为链接添加价值,但它一直返回 null。这是代码link.setAttribute('value', result[a].song_name);。对不起,我没有提到,song_link 和 song_name 是我数据库中的属性。
    猜你喜欢
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 2020-10-14
    • 2020-05-03
    • 2016-10-25
    • 2018-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多