2013-07-10 27 views
-1

我有两个div,类名为list_itemlist_item_menu。他们都被包含在另一个div类list_item_container。我可以使用以下方法来显示/隐藏list_item_menu点击list_item时:在jquery中切换动态创建的div

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

时的div都写在原始的HTML这工作,但动态创建的div时,则这种切换不起作用。我试着像这样创建它们:

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

但既不方式似乎工作。有任何想法吗?

+1

查看jQuery中的'。.on()'。基本上你想要委托事件。 – Robusto

回答

0

由于它们是动态创建的,你需要使用事件委托和绑定单击事件到DOM中已存在的元素:

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

Ca n成为:

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

现在阅读文档,并找出为什么这个工程。谢谢! – mattjulian

+0

@mattjulian - 很简单,您的点击处理程序是在DOM就绪功能中创建的。当您动态创建元素时,它们不在DOM准备好的位置,因此您的点击处理程序无法绑定到尚不存在的元素。 – tymeJV

0

在这种情况下,你应该使用on()

$(document).on('click', '.list_item', function() { 
    // Your code here 
}); 
0

使用上,而不是点击绑定事件

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