Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...