用于按钮的单击事件的选择器

What selector to use for the click event of a button

本文关键字:选择器 事件 单击 用于 按钮      更新时间:2023-09-26

在我的jQuery中,我添加了一系列li元素,每个li元素都有一个子元素按钮。我想做的是制作一个点击事件处理程序来附加到按钮上,当点击时,它将删除按钮及其父元素li。这是我的HTML:

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

这是我写的jQuery:

$("#add_task").click(function() {            
        //create a li, save input in there, and add to ol
        var new_task = $('<li></li>');
        new_task.text($("#add_todo").val());
        //new_task.attr('id', 'new_task');
        new_task.appendTo('ol.list');
        if (new_task)
        //create button and attach it to new li element
        var new_button = $('<input />').addClass('done');
        new_button.attr({
            type : "button",
            value : "Task Accomplished!"
        });
        new_button.appendTo(new_task);
    }
    $("#add_todo").val("").focus();
});
//end click event of Add task button
$('.done[value="Task Accomplished!"]').click(function() {
    $(function () {
        alert("This is working.");
    });
    //hide <li> element
    $(this).parentElement.remove();
    //if list is empty, show empty message
    if ($("#list li").length == 0)
        $("#empty_message").show();
    $("#add_todo").focus();
});
//end click event of Task Accomplished button

添加任务按钮(第一个功能)正在工作。我不明白为什么"任务完成"按钮不起作用!!有人能帮我吗?

$("#add_task").on('click', function() {            
    //create a li, save input in there, and add to ol
    var new_task = $('<li />', {
        text : $("#add_todo").val()
    });
    var new_button = $('<input />', {
        'class' : 'done',
        type    : 'button',
        value   : 'Task Accomplished!',
        on      : {
            click : function() {
                $(this).closest('li').remove();
                if ($("#list li").length == 0) {
                    $("#empty_message").show();
                }
                $("#add_todo").focus();
            }
        }
    });
    $('#list').append(new_task.append(new_button));
    $("#add_todo").val("").focus();
});

在创建元素时创建事件处理程序,并使用closest而不是parentElement