0

これがこのコードを書くのに最適な方法かどうかはわかりませんが、私が持っているものはほとんど機能します...

これは私がやろうとしていることです:

(1)<li></li>クリック時に要素を別の div に移動する

(2) 非表示の入力フィールドを追加または削除して更新します。<li id>

注:非表示の入力フィールドの値を置き換えたくはありませんが、「u40、u56、u98」の値で終わることができるように追加します...など...

そのため、ユーザーが<li>addable のクラスを持つ要素をクリックすると、その要素は親から削除され、別の div に<ul>追加されます。<ul>さらに、非表示の入力フィールドが<li>要素の ID で更新されます。<li>逆に、ユーザーがリムーバブルのクラスを持つ要素をクリックすると、反対のことが起こります...<li>はその親から削除<ul>され、他の要素に追加され、要素の id を削除することで非表示の入力フィールドが更新されます<li>...

これは私がこれまでに持っているものです...追加すると機能しますが、li.removable要素をクリックしても非表示の入力フィールドは値を削除しません。

$('li').click(function() {
    var uID = $(this).attr('id')+',';

    if($(this).hasClass("addable")) {

      $("input#edit-r").val($("input#edit-r").val() + uID);
      $(this).removeClass("addable");
      $(this).addClass("removable");
      $(this).appendTo($("#selections ul"));

    } else {
        var currentValue = $("input#edit-r").val();
        currentValue.replace(uID,"");
        $("input#edit-r").val(currentValue);
        $(this).removeClass("removable");
        $(this).addClass("addable");
        $(this).appendTo($(".filtered ul"));

    }
});

<div class="filtered">
    <ul>
        <li id="u40" class="addable">U40</li>
        <li id="u56" class="addable">U56</li>
        <li id="u98" class="addable">U98</li>   
    </ul>
</div>

<div id="selections">
    <ul>
    </ul>
</div>

<input type="hidden" id="edit-r" value="" />
4

2 に答える 2

1

選択が行われるたびに非表示の入力を更新しようとする代わりに、onsubmit ハンドラーにこの作業を任せてみませんか?

<form onsubmit="GetSelectedListIds()">

と:

function GetSelectedListIds() {
  var ids = [];
  $("li", "#selections").each(function() {
    ids[ids.length] = $(this).attr("id");
  });
  $("input#edit-r").val(ids.join());
}

このように、非表示の要素が選択したアイテムと同期していることを心配する必要はありません。

于 2011-04-30T18:40:29.367 に答える
1

変化する

currentValue.replace(uID,"");

currentValue = currentValue.replace(uID,"");

また、コードを最適化するために、jquery オブジェクトのチェーン機能を使用することもできます。

$(this).removeClass("addable").addClass("removable").appendTo("#selections ul");
于 2011-04-30T18:19:22.473 に答える