0

ボタンを含む各項目でソート可能な JQuery があります。ページの上部に、ソート可能に項目を追加する追加ボタンがあります。各ソート可能なボタンをプログラムして、その特定のアイテムの文字列をオートコンプリート (ページの上部) で現在のユーザーが入力した値に置き換えるようにしようとしています。これが私のコードです:

$(".addButton").click(function(e) {
e.preventDefault();
// set var item to be the string inputted by the user
var item = $("input[name='inputItem']").val(); //where 'inputItem' is the name of the <input>
// parses input string, splitting at commas into liArray containing substrings as elements
var liArray = item.split(", ");
// for loop to add each brew to the sortable list (length-1 because last element in array is empty string)
for (var i = 0; i < liArray.length-1; i++) {
    // sets var $li to the string in the ith index of liArray
    var $li = $("<li class='ui-state-default'/>").text(liArray[i]).append('<button class="replaceButton">Replace</button>');

    // adds var $li to gui
    $("#sortable").append($li);
};

$("#sortable").sort();

// refreshes the page so var $li shows up
$("#sortable").sortable("refresh");

});

追加した各アイテムに class = "replaceButton" のボタンがあるので、.js で次のように宣言するだけでよいと考えました。

$(".replaceButton").click(function() {
    // set var item to be the string inputted by the user
    var item = $("input[name='inputItem']").val();  //where 'inputItem' is the name of the <input>
    // I DON'T KNOW WHAT TO DO HERE
});

特定のアイテムの文字列にアクセスする方法がわからないため、そこからどこに行くべきかわかりません。「これ」を使うか?また、文字列を置き換えるだけでなく、特定のアイテムを削除して、その場所に新しいアイテムを作成した方が簡単でしょうか? あなたが持っている提案や答えをありがとう!

4

1 に答える 1

0

ボタンが の一部であることがわかっているためli、次のようにテキストにアクセスできます。

// mind the dynamic event binding!
$('#sortable').on('click', ".replaceButton", function(e) {
    e.preventDefault();

    var item = $("input[name='inputItem']").val();

    $(this).parent()
          .text(item)
          .append( $(this).clone() );
});

保持したい場合は、replaceButton の別のインスタンスを追加する必要があります。
また、ボタンを動的に追加するため、イベント バインディングの変更に注意してください。クリック イベントを永続的なコンテナーにバインドし、.replaceButtonまだ存在していない場合でも、すべてのインスタンスに動的にバインドします。

于 2013-04-15T18:59:37.127 に答える