简体   繁体   English

将每个 Li 元素转换成一个 object

[英]Convert each Li element into an object

I have an unordered list of players for a game that is dynamically generated by the user on the page.我有一个由用户在页面上动态生成的游戏的无序列表。 What I want to do is turn each list item into an object that will allow me to store their name and points.我想要做的是将每个列表项变成一个 object,这样我就可以存储他们的名字和分数。 Struggling with the code as I am still learning JS.由于我仍在学习 JS,因此在代码上苦苦挣扎。 I have got as far as the function to create each object but I don't know how to actual create an object for John, Paul, Ringo and George (or whoever else the user may add to the list)我已经得到 function 创建每个 object 但我不知道如何为 John、Paul、Ringo 和 George(或用户可能添加到列表中的任何其他人)实际创建 object

<ul id="playerList">
     <li>John</li>
     <li>Paul</li>
     <li>Ringo</li>
     <li>George</li>
</ul>  

const createPlayer = (playerName, points) => {return {name, points}}

Here is how you would get each of those li contents from your html and then do whatever you want to do with those datas:以下是如何从 html 中获取每一个li内容,然后对这些数据做任何您想做的事情:

var numberOfPlayers = getElementsByTagName('li').length;
for (i=0 ; i< numberOfPlayers; i++) {
var playerData document.getElementById('playerList').getElementsByTagName('li')[i].innerText;
// create your objects or do whatever you want with playerData
}

Based on Yishmeray suggestion you could also do it like that, among your preferences:根据 Yishmeray 的建议,您也可以根据自己的喜好这样做:

var playerData = document.querySelectorAll('#playerList li'); 
playerData.forEach(element => { 
var thisPlayerTxt = element.innerText;
//create your objects or do whatever you want with playerData
});

And just in case you would like to create a li and append it to your list:以防万一您想在列表中创建一个li和 append:

var list = document.getElementById('playerList');
var name = 'John';
var player = document.createElement('li');
player.innerText = name;
list.appendChild(player);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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