在jQuery中切换动态创建的div [英] toggling dynamically created divs in jquery

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

问题描述

我有两个div,分别具有类名称list_itemlist_item_menu.它们都包含在另一个list_item_container类的div中.单击list_item时,我可以使用以下内容显示/隐藏list_item_menu:

I have two divs with the class names list_item and list_item_menu. They are both contained in another div with the class list_item_container. I am able to use the following to show/hide list_item_menu when list_item is clicked:

$(".list_item").click(function() {
    $(this).next('.list_item_menu').toggle();
});

当div用原始html编写时有效,但是当div动态创建时,切换不起作用.我尝试过这样创建它们:

This works when the divs are written in the original html, but when the divs are created dynamically, the toggling does not work. I tried creating them like this:

function addListItem () {
var text = $("#new_item_field").val();
$("#list_box").children().last().after(
    '<div class = "list_item_container">'+
        '<div class = "list_item">'+
            text+
        '</div>'+
        '<div class = "list_item_menu">'+
            'notes | due | completed'+
        '</div>'+   
    '</div>'
);
$("#new_item_field").val('');
}

并这样:

function addListItemToDoc () {
var text = $("#new_item_field").val();

var listbox = document.getElementById('list_box');
var container = document.createElement('div');
    container.className = 'list_item_container';
var item = document.createElement('div');
    item.className = 'list_item';
    item.innerHTML = text;
var menu = document.createElement('div');
    menu.className = 'list_item_menu';
    menu.innerHTML = "notes | due | completed";

container.appendChild(item);
container.appendChild(menu);
listbox.appendChild(container);

    $("#new_item_field").val('');
}

,但似乎都没有办法.有什么想法吗?

but neither way seems to work. Any ideas?

推荐答案

由于它们是动态创建的,因此您需要使用事件委托并将click事件绑定到DOM就绪的元素:

Since they are created dynamically, you need to use event delegation and bind the click event to an element that is present at DOM ready:

$(".list_item").click(function() {

可以成为:

$("#list_box").on("click", ".list_item", function() {

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

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