admin管理员组

文章数量:1322850

I'm having trouble with a really simple script, consisting of a text box, button, and list of items. Clicking the button adds the text box value to the list. For some reason, though, the text is getting appended as pure text, and not inside of an li element. JSFiddle

 <form>                      

     <input type="text" class="form-control" placeholder="Task" id="text_task">

   <button type="submit" id="btn_add_task" class="btn btn-primary">Add Task</button>

</form>           

<ul id = "list_tasks">

</ul>      

JS:

function $(element) {
    return document.getElementById(element);
}

var taskSubmit = $('btn_add_task');
var taskBox = $('text_task');
var taskList = $('list_tasks');

taskSubmit.addEventListener('click', function(e) {
    e.preventDefault();
    var task = taskBox.value.trim();

    var newLI = document.createElement('li');
    var element = newLI.appendChild(document.createTextNode(task));

    taskList.appendChild(element);

    taskBox.value = '';

}, false);

I'm having trouble with a really simple script, consisting of a text box, button, and list of items. Clicking the button adds the text box value to the list. For some reason, though, the text is getting appended as pure text, and not inside of an li element. JSFiddle

 <form>                      

     <input type="text" class="form-control" placeholder="Task" id="text_task">

   <button type="submit" id="btn_add_task" class="btn btn-primary">Add Task</button>

</form>           

<ul id = "list_tasks">

</ul>      

JS:

function $(element) {
    return document.getElementById(element);
}

var taskSubmit = $('btn_add_task');
var taskBox = $('text_task');
var taskList = $('list_tasks');

taskSubmit.addEventListener('click', function(e) {
    e.preventDefault();
    var task = taskBox.value.trim();

    var newLI = document.createElement('li');
    var element = newLI.appendChild(document.createTextNode(task));

    taskList.appendChild(element);

    taskBox.value = '';

}, false);
Share Improve this question asked Sep 19, 2014 at 18:23 Tim AychTim Aych 1,3654 gold badges17 silver badges34 bronze badges 1
  • @Teemu because $() is typical jQuery selector syntax. – BenM Commented Sep 19, 2014 at 18:27
Add a ment  | 

1 Answer 1

Reset to default 7

It's because you're returning the textNode to element when you should be appending newLI

var newLI = document.createElement('li');

newLI.appendChild(document.createTextNode(task));

taskList.appendChild(newLI);

FIDDLE

本文标签: Appending an li to ul with vanilla JavaScriptStack Overflow