【问题标题】:Appending object key values to <li>将对象键值附加到 <li>
【发布时间】:2016-09-14 17:51:55
【问题描述】:

更新:我用类编辑了 li,使其更容易理解和抓取。

我进行了相当彻底的搜索,但找不到我要找的确切内容。我的 HTML 中有一系列下拉选择框,目前没有填充。

<li class="games-owned">
    <div class="input-field col s6">
        <select>
            <option value="" disabled selected>What Game Do You Want To Trade?</option>
        </select>
    </div>
</li>
<li class="games-wanted">
    <div class="input-field col s6">
        <select>
            <option value="" disabled selected>What Game Would You Like To Have?</option>
        </select>
    </div>
</li>
<li class="city">
    <div class="input-field col s12">
        <select>
            <option value="" disabled selected>What City Do You Live In?</option>
        </select>
    </div>
</li>

我需要用我的 main.js 模拟数据中的键值对的内容填充它们,这里:

var mockData = {
"profile": [{
    "name": "Mario",
    "city": "Los Angeles",
    "state": "California",
    "gameOwned": "Grand Theft Auto 5 (PS4)",
    "gameWanted": "Battlefield 4 (PS4)",
    "publishedAt": new Date()
}, {
    "name": "Colin",
    "city": "Los Angeles",
    "state": "California",
    "gameOwned": "Battlefield 4 (PS4)",
    "gameWanted": "Grand Theft Auto 5 (PS4)",
    "publishedAt": new Date()
}],
"city": ["Los Angeles", "New York"],
    "game": ["Battlefield 4 (PS4)", "Grand Theft Auto 5 (PS4)"]
}

特别是前两个li需要从“game”中剔除,最后一个li需要从“city”中剔除。显然,这三个过程大致相同。

我尝试过使用 for 循环,但我不确定首先应该连接什么或连接什么或如何连接。我比较新。非常感谢您的建议。

【问题讨论】:

  • 在你问之前尝试一下是个好主意。
  • 您是否尝试将mockData 集合中的元素插入到三个选择元素中。如果是这样,您希望显示哪些数据,您希望哪些数据成为每个新选项的值?您是否计划将每个项目的所有数据填充到选项中(可见或不可见),还是希望稍后确定哪条数据对应于任何给定的选择?
  • 我正在尝试获取 mockData.game 数组中的每个项目,并将每个项目作为自己的选项附加到 games-wantedgames-owned li 中。我想对 mockData.city 数组项做同样的事情并将它们附加到city li。
  • 所以在我第一次尝试时,我不明白您对个人资料数据做了什么 - 所以第二次尝试最终要简单得多。

标签: javascript html object for-loop


【解决方案1】:

我的建议是:

var mockData = {
  "profile": [{
    "name": "Mario",
    "city": "Los Angeles",
    "state": "California",
    "gameOwned": "Grand Theft Auto 5 (PS4)",
    "gameWanted": "Battlefield 4 (PS4)",
    "publishedAt": new Date()
  }, {
    "name": "Colin",
    "city": "Los Angeles",
    "state": "California",
    "gameOwned": "Battlefield 4 (PS4)",
    "gameWanted": "Grand Theft Auto 5 (PS4)",
    "publishedAt": new Date()
  }],
  "city": ["Los Angeles", "New York"],
  "game": ["Battlefield 4 (PS4)", "Grand Theft Auto 5 (PS4)"]
}

window.addEventListener('DOMContentLoaded', function(e) {
 mockData.game.forEach(function(value, index) {
    document.querySelectorAll('li:nth-child(1) select')[0].innerHTML += '<option value="' + value + '">' + value + '</option>';
    document.querySelectorAll('li:nth-child(2) select')[0].innerHTML += '<option value="' + value + '">' + value + '</option>';
 });
 mockData.city.forEach(function(value, index) {
    document.querySelectorAll('li:nth-child(3) select')[0].innerHTML += '<option value="' + value + '">' + value + '</option>';
  });
});
<li>
    <div class="input-field col s6">
        <select>
            <option value="" disabled selected>What Game Do You Want To Trade?</option>
        </select>
    </div>
</li>
<li>
    <div class="input-field col s6">
        <select>
            <option value="" disabled selected>What Game Would You Like To Have?</option>
        </select>
    </div>
</li>
<li>
    <div class="input-field col s12">
        <select>
            <option value="" disabled selected>What City Do You Live In?</option>
        </select>
    </div>
</li>

【讨论】:

  • jQuery 没有被标记。
  • @RobertParham 我一会儿用纯 javascript 翻译它。给我一秒钟。你能删除反对票吗?
  • @RobertParham 现在看看。我是对的。如果你现在说不,我可以删除我的答案。这并不完美。非常感谢您的评论。
  • @RobertParham 再次感谢。
  • @gaetanoM,哇,谢谢。奇迹般有效。这里有很多我不明白的地方,我以前从未见过。我将查看相关文档。
【解决方案2】:

演示:https://jsfiddle.net/fvxm0tvd/

为您的选择添加一个 ID,以便您可以访问它们,执行标准 for 循环以遍历数据集,使用 innerHTML&lt;option&gt;s 附加到每个。

var want = document.getElementById('want');
for(var i=mockData.profile.length; i--;)
    want.innerHTML += "<option>"+mockData.profile[i].gameWanted+"</option>";

【讨论】:

  • 哎哟!像这样设置innerHTML会导致浏览器做更多的工作,元素不需要ID就可以访问它们,并且你的for循环以相反的顺序添加元素。
  • 是的,我知道。我可以将 html 块放在一个数组中,然后用 join() 附加它们,可以使用 insertadjacenthtml,可以选择字节标记名称并通过所有选择元素进行交互,可以使用类名代替.. 可以上升循环而不是下降。只是一个简单的例子。
【解决方案3】:

我可能会建议修改您的个人资料数据结构:

"profile": [{
    "name": "Mario",
    "city": "Los Angeles",
    "state": "California",
    "game": {"owned":["Grand Theft Auto 5 (PS4)"],
             "wanted":["Battlefield 4 (PS4)"]},
    "publishedAt": new Date()
}

var mockData = {
"profile": [{
    "name": "Mario",
    "city": "Los Angeles",
    "state": "California",
    "gameOwned": "Grand Theft Auto 5 (PS4)",
    "gameWanted": "Battlefield 4 (PS4)",
    "publishedAt": new Date()
}, {
    "name": "Colin",
    "city": "Los Angeles",
    "state": "California",
    "gameOwned": "Battlefield 4 (PS4)",
    "gameWanted": "Grand Theft Auto 5 (PS4)",
    "publishedAt": new Date()
}],
"city": ["Los Angeles", "New York"],
    "game": ["Battlefield 4 (PS4)", "Grand Theft Auto 5 (PS4)"]
}

// The property names in the data that have associated select(s)
var fields = [ "city", "game" ];

function init() {
    // For each property
    fields.forEach( field => {
        // Find all the selects that are children of a list item with a class that starts with the field name
        document.querySelectorAll('li[class^='+field+'] select').forEach( select => {
            // Add a new option for every element in the field
            mockData[field].forEach( text => select.appendChild(new Option(text)))
        });
    });
}

document.addEventListener( "DOMContentLoaded", init, false );
<body>
<li class="games-owned">
    <div class="input-field col s6">
        <select>
            <option value="" disabled selected>What Game Do You Want To Trade?</option>
        </select>
    </div>
</li>
<li class="games-wanted">
    <div class="input-field col s6">
        <select>
            <option value="" disabled selected>What Game Would You Like To Have?</option>
        </select>
    </div>
</li>
<li class="city">
    <div class="input-field col s12">
        <select>
            <option value="" disabled selected>What City Do You Live In?</option>
        </select>
    </div>
</li>
</body>

【讨论】:

    【解决方案4】:

    首先我会为不同的选择元素上课

    <li>
        <div class="input-field col s6">
            <select class="select-game">
                <option value="" disabled selected>What Game Do You Want To Trade?</option>
            </select>
        </div>
    </li>
    <li>
        <div class="input-field col s6">
            <select class="select-game">
                <option value="" disabled selected>What Game Would You Like To Have?</option>
            </select>
        </div>
    </li>
    <li>
        <div class="input-field col s12">
            <select class="select-city">
                <option value="" disabled selected>What City Do You Live In?</option>
            </select>
        </div>
    </li>
    

    然后将 json 映射到选项元素 -

    var gameSelects = document.querySelectorAll('.select-game');
    
    for (var i=0; i<gameSelects.length; i++) {
        mockData.game.map(function(game) {
            var option = document.createElement("OPTION");
            var textnode = document.createTextNode(game);
            option.appendChild(textnode);
            gameSelects[i].appendChild(option);
        })
    }
    

    对城市选择做同样的事情

    【讨论】:

    • 打错了...gameSelects[i].appendChild(node); 节点应该是选项
    • @naotor,感谢您的回答。我是不是误会了什么?我的控制台说节点未定义 @gameSelects[i].appendChild(node);我应该向那个 arg 传递一些东西吗?
    • @ColinAulds - 阅读其他 cmets。我只是指出了错字。 node 实际上应该是 option
    猜你喜欢
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多