将代码从console.log转换为innnerHTML(以HTML格式显示)

时间:2018-04-13 01:12:12

标签: javascript html arrays list

我正在尝试使用JS在html中构建一个待办事项列表。

我可以在谷歌浏览器的控制台中准备一个列表,但我不知道用于打印"列表"的语法。到浏览器。

请看下面的代码:



window.setTimeout(function() {
    var myCurrentList = [];
    while (true) {
        var questionAsked = prompt("please tell tell me what do you want to do");
        var userInput = ""
        if (questionAsked.toLowerCase() === "new") {
            userInput= prompt("enter the task")
            myCurrentList.push(userInput);

        }

        else if (questionAsked.toLowerCase() === "list") {
            for (var i = 0; i < myCurrentList.length ; i++) {
                console.log( (i+1) + '. ' + myCurrentList[i]);
            }
        }

        else if (questionAsked.toLowerCase() === "quit") {
            console.log("Thank you!");
            break
        }

        else {
            alert("please use the text from only 3 given options")
        }
    }
}, 500);
&#13;
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Interactive ToDo List</title>

</head>
<body>
<h1>ToDo List Instructions</h1>
<ol>
    <li>to add a ToDo task please type "new"</li>
    <li>to view your current list please type "list"</li>
    <li>when done and want to quit,please type "quit"</li>
</ol>

<p id="infoSection"></p>

<script type="text/javascript" src="toDoListJS.js"></script>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

添加元素的更安全的方法是使用DOM API(google&#39; mdn dom api&#39;)。

var myList = document.getElementById('my-list'); var newListItem = document.createElement('li'); newListItem.textContent = 'List item text.'; myList.appendChild(newListItem);

此页面是一个很好的介绍:https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction