使用javascript / jquery创建<li>元素并将其添加到有序列表中

时间:2015-12-09 08:05:49

标签: javascript jquery html

我尝试创建待办事项列表,当用户输入新任务并单击按钮时,javascript应创建一个包含持有用户条目的跨度的li元素,然后在我的HTML中将li元素添加到ol中。 我的HTML看起来像这样:

<body>
    <h1>To Do:</h1>
    <section>

        <input type="text" id="add_todo">
        <span id="add_task_error">&nbsp;</span>
        <input type="button" id="add_task" value="Add task">

        <div id="empty_message" class="open">
            <h3>You have no tasks left to accomplish!</h3>
        </div>

        <div id="tasklist">
            <ol class="list">

            </ol>
        </div>

    </section>
</body>

这是无效的功能:

        var newSpan = $('<span>input</span>').addClass("task");
        //wrap it in a <li> element
        newSpan = (".task").wrap("<li></li>");
        $(".list").append(newSpan);

我也是这样试过的:

         var new_task = $('<li>*</li>').addClass('task');
         new_task.appendTo('ol.list');
         new_task.setAttribute('id', 'new_task');
         $("#new_task").text(input);

当我点击添加任务按钮(这不是问题 - 我测试过它)时,两种方式都不起作用,屏幕上没有任何反应......

我做错了什么???

5 个答案:

答案 0 :(得分:2)

试试这个

&#13;
&#13;
$(document).ready(function(){
  $('#add_task').click(function(){
    var task = $('#add_todo').val();
    var html = '<li><span>'+task+'</span></li>';
    $('.list').append(html);
  })
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>To Do:</h1>
    <section>

        <input type="text" id="add_todo">
        <span id="add_task_error">&nbsp;</span>
        <input type="button" id="add_task" value="Add task">

        <div id="empty_message" class="open">
            <h3>You have no tasks left to accomplish!</h3>
        </div>

        <div id="tasklist">
            <ol class="list">

            </ol>
        </div>

    </section>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这应该是你的代码。 单击按钮调用addLI()

<input type="button" id="add_task" value="Add task" onclick="addLI()">

function addLI() {
    //check for empty value
    if ($('#add_todo').val() == "") {
        alert("Please Add Todo.");
        return;
    }
    //generate html for li
    var html = "<li class='task' id='new_task'><span>" + $('#add_todo').val() + "</li>";

    //append li to order list
    $(".list").append(html);
}

答案 2 :(得分:0)

希望这适合你

JS代码:

$("#add_task").click(function(){
    var value = $("#add_todo").val();
    $(".list").append("<li class='task'><span>"+ value +"</span></li>")
});

这是工作Plnkr

答案 3 :(得分:0)

创建元素,设置所有属性,完成后,将其添加到ol

var new_task = $('<li></li>').addClass('task');
new_task.text($("#add_todo").val()); //this is the value of the input
new_task.attr('id', 'new_task'); //use attr instead of setAttribute    
new_task.appendTo('ol.list');

<强> FIDDLE

答案 4 :(得分:0)

在添加任何新任务之前,还要尝试隐藏显示消息的div。

<div id="empty_message" class="open">
            <h3>You have no tasks left to accomplish!</h3>
        </div>
关于添加任务的点击事件

$('.open').hide();