2012-02-27 59 views
1

我想用jQuery动态生成的div标签添加由div生成的div标签元素。我的代码如下所示:如何将由jQuery生成的div标签动态添加到javascript div标记元素

$(".remove_item").click(function(){ 
    $(this).hide("fast", function(){ 
    var id = $(this).parent().attr("id"); 
    var remove_item_id = document.getElementById(id); 
    var block_element = document.getElementById("block"); 

    block_element.removeChild(remove_item_id); 

    new_item = $("<div/>"); 
    new_item.attr("id", "item"); 
    new_item.attr("name", "item"); 
    new_item.addClass("div_image"); 
    new_item.append($("<img/>") 
    .addClass("image") 
    .attr("src", "/compare/sites/default/files/add_item.jpg") 
    .attr("height", 50) 
    .attr("width", 50)); 

    new_item.append($("<span/>") 
    .addClass("new_item") 
    .click(function(){ 
    $(this).parent().remove(); 
    })); 

    block_element.append(new_item); 
}); 
}); 

的附加jQuery的div标签代码使用javascript div标签应该是这样的: block_element.append(NEW_ITEM);

但它给错误,因为我们不能绑定,因为我在同一行使用JavaScript和jQuery。有什么办法可以做到吗?

回答

1

的唯一的事情,你需要改变的是

var block_element = $("#block"); 
$("#"+remove_item_id).remove(); 

休息应该照原样。

0

您只需要在jQuery选择器中传递该元素。

首先溶液(当您将追加):

$(block_element).append(new_item); 

二溶液(当您选择元素)

var block_element = $("#block"); 
+1

第二种解决方案将打破'removeChild'。 – bfavaretto 2012-02-27 04:26:30

+0

即使第一个解决方案也不行 – Starx 2012-02-27 04:35:50

1

你需要做的是你应该将JavaScript元素转换为一个jQuery对象。

  1. $(block_element)可以将JavaScript元素转换为jQuery对象;
  2. 相反$(block_element)[0]可以将jQuery对象转换为JavaScript元素。
0
$(".remove_item").click(function(){ 
    $(this).hide("fast", function(){ 
     var elm = $("#block"), 
      parent = $(this).parent(), 
      img = $('<img src="/compare/sites/default/files/add_item.jpg" class="image" height="50px" width="50px" />'), 
      span = $('<span class="new_item"></span>'), 
      new_item = $('<div id="item" name="item" class="div_image"></div>').append(img).append(span); 

     elm.remove(parent).append(new_item).on('click', function(){ $(this).parent().remove(); }); 
}); 
相关问题