1

私のスクリプトでは、要素 (リスト) をある親 (テキストのみ) から別の親 (リスト) に移動してから、再び (リストに) 移動しようとしています。問題は、要素を元の親 (ul) に戻すと、クリックできなくなることです。remove() よりも detach() を使用するとうまくいくかもしれないと思いましたが、違いはありません。

$(document).ready(function() {
  $("#inventoryWeapon li").click(function(event) { 
    var clickedId = event.target.id;
    if ($("td#weapon").is(":empty")) {
      $("td#weapon").text(clickedId); 
      $(this).detach(); 
    }
  });
  $("td#weapon").click(function(event) { 
    var unequipping = $(this).text();
    $("#inventoryWeapon").append("<li id='" + unequipping + "'>" + unequipping + "</li>"); 
    $(this).detach();
  });
});
4

2 に答える 2

2

上記の一般的なコメントで示唆されているように、要素を移動していません。移動するには、次のようにします。

$("td#weapon").click(function(event) {
    $(this).appendTo($("#inventoryWeapon"));
});
于 2013-10-22T20:23:32.307 に答える
2

要素を移動するのではなく、一方の関数で要素を削除し、もう一方の関数で同じ ID とコンテンツを持つ新しい要素を作成しています。しかし、元のイベント ハンドラーは元の要素にのみバインドされていました。

イベント ハンドラーを動的に作成された要素で動作させたい場合は、イベント デリゲートを使用します。

$("#inventoryWeapon").on("click", "li", function(event) {
    ...
});

または、要素を再作成する代わりに、デタッチ時に要素を保存することもできます。

var savedLI;
$("#inventoryWeapon li").click(function() {
    if ($("td#weapon").is(":empty")) {
        savedLI = $(this).detach();
        $("td#weapon").text(this.id);
    }
});
$("td#weapon").click(function() {
    if (savedLI) {
        $("#inventoryWeapon").append(savedLI);
        $(this).detach();
    }
});
于 2013-10-22T20:24:06.240 に答える