【问题标题】:toggling dynamically created divs in jquery在jquery中切换动态创建的div
【发布时间】:2013-07-10 17:47:38
【问题描述】:

我有两个类名为 list_itemlist_item_menu 的 div。它们都包含在另一个具有list_item_container 类的 div 中。当点击list_item 时,我可以使用以下内容显示/隐藏list_item_menu

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

但这两种方法似乎都行不通。有什么想法吗?

【问题讨论】:

  • 在 jQuery 中查看 $.on()。基本上你想委托事件。

标签: jquery


【解决方案1】:

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

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

可以变成:

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

【讨论】:

  • 现在阅读文档并弄清楚为什么这样做。谢谢!
  • @mattjulian -- 很简单,您的点击处理程序是在 DOM 就绪函数中创建的。当您动态创建元素时,它们在 DOM 中并不准备就绪,因此您的点击处理程序无法绑定到尚不存在的元素。
【解决方案2】:

在这些情况下,您应该使用on()

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

【讨论】:

    【解决方案3】:

    使用on代替点击绑定事件

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多