jQuery-选择动态创建的div [英] jQuery - selecting dynamically created divs

查看:116
本文介绍了jQuery-选择动态创建的div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个快速的jQuery问题:

I have a quick jQuery question:

首先,我的HTML:

<div id="taskinput">
    <form>
         <input id="taskinput-box" type="text"></input>
         <input type="submit"></input>
    </form>
</div><!-- end taskinput -->
<div id="taskoutput"></div><!-- end taskoutput -->

我正在使用.append在用户创建的#task输出中创建内容,同时创建了一个新类.task.

I am creating content in the #taskoutput from user using .append while creating a new class, .task.

$("#taskinput").submit(function() {
    var tasktext = $('#taskinput-box').val()
    $('#taskoutput').append('<div class="task">'+tasktext+'</div>');
    $('#taskinput-box').val("");
    return false;
});

上面的代码工作正常;当我尝试选择创建的div时会出现麻烦.以下代码不起作用:

The above code works fine; the trouble arises when I try to select the created divs. The below code does not work:

$(".task").click(function() {
    $(this).slideUp();
});

我想念什么?

推荐答案

您必须像on一样使用delegate event:

$('#taskoutput').on('click', '.task', function(){
    $(this).slideUp();    
});

@salek 演示 但带有on

阅读 on文档:

事件处理程序仅绑定到当前选定的元素;当您的代码调用.on()时,它们必须存在于页面上.为了确保元素存在并可以选择,请在文档就绪处理程序内对页面上HTML标记中的元素执行事件绑定.如果要在页面中注入新的HTML,则在将新的HTML放入页面后,选择元素并附加事件处理程序.或者,使用委托事件来附加事件处理程序,如下所述.

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.

委派事件的优点是,它们可以处理以后添加到文档中的后代元素中的事件.通过选择保证在附加委托事件处理程序时会出现的元素,您可以使用委托事件来避免频繁附加和删除事件处理程序的需要.例如,如果事件处理程序想要监视文档中的所有冒泡事件,则此元素可以是Model-View-Controller设计中视图的容器元素,也可以是文档.在加载任何其他HTML之前,文档元素位于文档的开头,因此可以在其中附加事件,而不必等待文档准备就绪.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

这篇关于jQuery-选择动态创建的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆