2012-02-27 26 views
1

jQueryで生成されたdivタグをjavascriptの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); 
}); 
}); 

のdivタグは次のようになりますJavaScriptでのjQueryの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

第2の解決策は、「removeChild」を中断します。 – bfavaretto

+0

最初のソリューションでも機能しません – Starx

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(); }); 
}); 
関連する問題