2

我发现代码按我的预期工作(我认为)。但是我打印数据的最后一步感觉不对。我连接 html 和 js 的方式似乎有点不对劲。有没有更好的方法来连接它?我是否使用了错误的解决方案来打印数据?

// 这个列表我在我的数组中使用。

    const myList = {
        Germany : {name : 'Germany', capital: 'Berlin', visited: 'Checked' },
        Italy : {name : 'Italy', capital: 'Rome', visited: 'Checked' },
        Spain : {name : 'Spain', capital: 'Madrid', visited: 'unchecked' },
    }

// 我的数组

    const destinations = [];

// 将数据从 myList 推送到目标数组。

    for(var key in myList) {
        destinations.push(myList[key]);
    }

// 这就是在页面上写出我的数据的方式。

    for (var i = 0; i < destinations.length; i++) {
    document.write("<li><h1>" + destinations[i].name + "</h1><p>" + 
                   destinations[i].capital + 
                   "<input type='checkbox'" + destinations[i].visited + ">")
    };

这就是我打算在最后写出来的。

<li class="all-destinations">
    <h3>destinations[i].name</h3>
    <div class="container">
        <label class="switch">
        <input type="checkbox" destinations[i].visited>
        </label>
    </div>
    <p>destinations[i].capital</p>
    <hr>
</li>
4

2 回答 2

1

您通过三种方式使您的代码变得更好:

  • 使用Object.values()而不是创建[]和推送它。
  • 您可以使用forEach()而不是简单的 for 循环
  • 您应该使用模板字符串来创建 html 字符串。

const myList = {
        Germany : {name : 'Germany', capital: 'Berlin', visited: 'Checked' },
        Italy : {name : 'Italy', capital: 'Rome', visited: 'Checked' },
        Spain : {name : 'Spain', capital: 'Madrid', visited: 'unchecked' },
    }
    
const list = Object.values(myList);

list.forEach(x => {
  document.write(
  `<li class="all-destinations">
      <h3>${x.name}</h3>
      <div class="container">
        <label class="switch">
          <input type="checkbox" ${x.visited}>
        </label>
      </div>
      <p>${x.capital}</p>
      <hr>
  </li>`)
})

于 2019-05-12T07:37:11.880 回答
0

document.write如果页面已经完全加载,您可以直接将值分配给 innerHTML 属性,否则可能无法正常工作。

function getItems({ name, capital, visited }) {
    return `<li class="all-destinations">
        <h3>${name}</h3>
        <div class="container">
            <label class="switch">
                <input type="checkbox" ${visited}>
            </label>
        </div>
        <p>${capital}</p>
        <hr>
    </li>`;
}


const myList = { Germany: { name: 'Germany', capital: 'Berlin', visited: 'Checked' }, Italy: { name: 'Italy', capital: 'Rome', visited: 'Checked' }, Spain: { name: 'Spain', capital: 'Madrid', visited: 'unchecked' } };

document.getElementById('list').innerHTML += Object.values(myList).map(getItems).join('');
<ul id="list"></ul>

于 2019-05-12T07:45:53.353 回答