Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

toggling dynamically created divs in jquery

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();
});

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('');
}

and like this:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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() {

Can become:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...