简体   繁体   English

Javascript使用数组将li添加到ul

[英]Javascript add li to ul using array

I am working on a spelling game for my children, and I want to display a spelling list based on what they enter and an array that is created. 我正在为我的孩子们进行拼写游戏,我想根据他们输入的内容和创建的数组显示一个拼写列表。 Here is the link to my project on github https://github.com/urock24/myWebSite.git 这是我在github https://github.com/urock24/myWebSite.git上的项目的链接

Here is the code in question, javascript first 这是有问题的代码,首先是javascript

function populateSpellList() {      
    // for loop should run through spelling list array and create list items in "listSpelling"

    for (var i = 0; i < spellingList.length; i++ ) {
        // create a new li
        var newLI = document.createElement("li");
        var indSpellingWord = spellingList[i];

        // grab the spelling list item 
        var newContent = document.createTextNode(indSpellingWord);

        // add the spelling list item to the li
        newLI.appendChild(newContent);

        // get the unordered list and add the new li
        var displaySpellList = document.getElementById("listSpelling");     

        displaySpellList.appendChild(newLI);
    }   
}

And the HTML 和HTML

<div id = "theSpellingList">

            <h3>The Spelling List</h3>
            <ul id = "listSpelling">
               <li>test </li>
            </ul>

        </div>

I can get an alert to pop up for me after every line in the function except the last, and it only seems to pop up once. 在函数的每一行(最后一行除外)之后,我都可以弹出警报,并且似乎只弹出一次。 But no matter what happens it is not displaying any list items in that list. 但是无论发生什么情况,它都不会在该列表中显示任何列表项。

I have seen a lot of jquery examples on here so I am definitely going to be pursuing learning jquery, but for now "plain" javascript would be great. 我在这里看到了很多jquery示例,因此我肯定会追求学习jquery,但是就目前而言,“纯文本” javascript会很棒。

From what I can see, you're trying to insert elements into the document which is embeded via iFrame. 据我所知,您正在尝试将元素插入通过iFrame嵌入的文档中。 But you can't do this that simple. 但是,您无法做到这一点。 The thing is that when you call document.getElementById from the parent (not iframe) window, it tries to find an element within parent window. 问题是,当您从父窗口(而非iframe)窗口调用document.getElementById时,它将尝试在父窗口中查找元素。 But iFrame is a separate window. 但是iFrame是一个单独的窗口。

You can try following. 您可以尝试关注。

In every specific game html file: 在每个特定的游戏html文件中:

<body>
  <!-- SOME CONTENT HERE -->

  <!-- RIGHT BEFORE `BODY` CLOSE -->
  <script>
    // This will run your code once document is loaded.
    window.onload = function () {
        // run the createName function
        createName();
        // run the createList function 
        createList();
        //play game
        playGame(target);
    };
  </script>
</body>

In learningGames.js : learningGames.js中

function populateSpellList() {  

    // for loop should run through spelling list array and create list items in "listSpelling"
    var i;
    for (i = 0; i < spellingList.length; i++ ) {

        var newLI = document.createElement("li"), // create a new li
            displaySpellList = document.getElementById("listSpelling"), // cache the unordered list
            newContent = document.createTextNode(spellingList[i]); // grab the spelling list item

        // add the spelling list item to the li
        newLI.appendChild(newContent);

        displaySpellList.appendChild(newLI);
    }
}

function gameWindow(target) {
    // set the iframe html to the target html 
    document.getElementById('game_frame').src = target;
}

Hope it is exactly what you need. 希望这正是您所需要的。

More of a comment than answer, your basic code seems to work fine with some added test data. 注释多于答案,基本代码似乎可以与某些添加的测试数据一起正常工作。 Below are some suggestions on making the code a little more concise: 以下是一些使代码更简洁的建议:

<script>

// List of words
var spellingList = ['foo','bar','fum'];

function populateSpellList() {

  // Get list once and store reference
  var list = document.getElementById("listSpelling");

  // Declare variables once, near top is good
  var li;

  // for loop should run through spelling list array and create list items in "listSpelling"
  for (var i = 0; i < spellingList.length; i++ ) {

    // Create new LI
    li = document.createElement("li");

    // Append the spelling word
    li.appendChild(document.createTextNode(spellingList[i]));

    // Add to list
    list.appendChild(li);
  }
}

// Call the function when the document is ready
window.onload = populateSpellList;
</script>

<div id = "theSpellingList">
  <h3>The Spelling List</h3>
  <ul id = "listSpelling">
    <li>test </li>
  </ul>
</div>

You can do the above in fewer lines of code, however it becomes a bit unmanageable. 您可以用更少的代码行来完成上述操作,但是这变得有些难以管理。 Less code isn't always "better". 更少的代码并不总是“更好”。

You could do this. 你可以做到这一点。 Make sure your JS is placed after the HTML, or put it in a window.onload function. 确保将JS放在HTML后面,或将其放在window.onload函数中。

var listEl = document.getElementById('listSpelling');

var spellingList = ['word1', 'word2', 'word3', 'word4'];

var populateList = function(arr){
    var str = '';
    for(var i = 0; i < arr.length; i++){
        str += '<li>' + arr[i] + '</li>';
    }
    return str;
}

listEl.innerHTML = populateList(spellingList);

Fiddle 小提琴

 function populateSpellList( arr ) { // Pass the Array as argument. var UL = document.getElementById("listSpelling"), // Get UL outside of the loop. LI = ""; for (var i=0; i<arr.length; i++) { LI += '<li>'+ arr[i] +'</li>'; // concatenate LIs inside the loop. } UL.insertAdjacentHTML('beforeend', LI); } populateSpellList( [ "Word1", "Word2", "Word3" ] ); 
 <ul id="listSpelling"><li>test</li></ul> 

https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentHTML https://developer.mozilla.org/zh-CN/docs/Web/API/Element.insertAdjacentHTML

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

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