繁体   English   中英

使用jQuery删除附加元素

[英]Deleting appended element with jQuery

我正在尝试开发一个简单的待办事项应用程序,但是使用jQuery创建的元素无法使用我设置的快捷键删除。 我创建的短按键在第一个元素(以及从头开始的其他元素)上工作,但是通过jQuery进入DOM的元素无法删除。

<script>
    $(document).ready(function() {
        $('textarea.todo').focus(function () {
            $(this).elastic();
        });

        $('textarea.todo').focusout(function () {
            $(this).animate({ height: "2em" }, 500);
            $(this).scrollTop(0);
        });

        $('#addTodo').click(function(){
            $('<textarea class="todo" rows="1"></textarea>').appendTo('#todos');
        });

        $('.todo').bind('keydown', 'alt+ctrl+d', function(){
            $(this).fadeOut('Slow');
        });
    });
</script>
</head>

<body>
    <div id="header">
        Simple<span id="alt">TODO</span>
    </div>
    <div id="todos">
        <textarea class="todo" rows="1"></textarea>
    </div>
    <div id="footer">
        <div class="left"><img src="PlusSign.png" id="addTodo"/></div>
        <div class="right">HELP</div>
    </div>
$('.todo').bind('keydown', 'alt+ctrl+d', function(){
                                    $(this).fadeOut('Slow');
                    });

这里使用on()而不是bind 在这种情况下,将自动订阅新创建的元素。

$(document).on('keydown', '.todo', function(e){    
        if (e.ctrlKey && e.altKey && e.keyCode == 68)
            $(this).fadeOut('Slow');
});

代码: http//jsfiddle.net/FgZaR/3/

答案基本上是在添加处理程序之后添加元素(元素不存在),在这种情况下,根据您的jQuery版本,您可以使用一些选项。

这将记录事件,即使它们是在您进行初始绑定后添加的。

只是当您使用AddTodo方法添加元素时,不会在其上附加快捷方式事件。

$('#addTodo').click(function(){
    $('<textarea class="todo" rows="1"></textarea>').appendTo('#todos').bind('keydown', 'alt+ctrl+d', function(){
        $(this).fadeOut('Slow');
    });
});

我是这样做的,它有效:

            $('#addTodo').click(function(){
            $('<textarea class="todo" rows="1"></textarea>').appendTo('#todos');
            $('.todo').bind('keydown', 'alt+ctrl+d', function(){
                $(this).fadeOut('Slow');
            });
        });

可能不是最好的解决方案,但它至少可以工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM