使用jQuery添加列表项后删除列表项

c

我在使用jquery添加列表项后单击删除列表项时遇到一些问题。如果我不得不猜测为什么会这样,那是因为jquery可能正在查看我的原始HTML文档,而不是添加列表项之后的更新文档?无论哪种方式,我都不知道如何解决。

这是我的HTML:

<form>
        <div>
            <label for="todo">I need to:</label>
            <input type="text" id="todo" />
        </div>
        <button id ="add" type="button">Add to your to-do list!</button>
</form>
<ul>
</ul>

而我的jQuery:

$(document).ready(function() {
    $('#add').click(function() {
        var item = $('#todo')
        $('ul').prepend("<li>"+item.val()+"</li>");
    });
        $('li').click(function() {
        $(this).remove();
    });
});
阿伦·P·约翰尼

由于您尝试为动态添加的元素添加事件处理程序,因此需要使用事件委托

$(document).ready(function() {
    $('#add').click(function() {
        var item = $('#todo')
        $('ul').prepend("<li>"+item.val()+"</li>");
    });
    $('ul').on('click', 'li', function() {
        $(this).remove();
    });
});

演示:小提琴

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章