0

jqueryを使用してこのリンクのIDをその場で変更するのに問題があります。リンクテキストは変更できますが、IDは変更できません。何か案は?

<a href="#" id="follow-5">follow</a>

リンクをクリックすると、次のように表示されます。

<a href="#" id="following-5">following</a>

これが私のjqueryコードです

$("a[id^='follow']").live('click', function(e) {
    e.preventDefault();
    var aid = $(this).attr('id').substring(7);
    $.ajax({
        type: "POST", url: "/artist/", data: "command=becomeFan&aid=" + aid,
        dataType: "html",
        success: function(data){
            $("#follow-" + aid).text("Following");
            $("#follow-" + aid).prev("a").attr("id","following-" + aid);
        }
    });
    return false;
});
4

1 に答える 1

2

問題は、コードがその要素のIDを変更しようとせず、要素のIDを変更しようとすること.prev()です。だから変更:

$("#follow-" + aid).prev("a").attr("id","following-" + aid);

に:

$("#follow-" + aid).attr("id","following-" + aid);

そしてそれはうまくいくはずです。.attrただし、呼び出しをチェーンする前に、行で同じ要素をすでに選択している場合は、次のようになります。

        $("#follow-" + aid).text("Following")
                           .attr("id","following-" + aid);

または、要素をidで再選択するのではなく、Ajax呼び出しを行う前に要素への参照を保存します。

$("a[id^='follow']").live('click', function(e) {
    e.preventDefault();
    var $this = $(this),
        aid = $this.attr('id').substring(7);
    $.ajax({
        type: "POST", url: "/artist/", data: "command=becomeFan&aid=" + aid,
        dataType: "html",
        success: function(data){
            $this.text("Following").attr("id","following-" + aid);
        }
    });
    return false;
});

また、selector withで始まる属性の使用は、$("a[id^='follow']")IDが変更された後もこれらの要素を選択し続けますが、IDを変更した後.substring(7)は、最後からIDを取得するために使用することはできません$("a[id^='follow-']")クリックハンドラーがまだクリックされていないリンクでのみ機能するように、これを変更することをお勧めします。

于 2012-08-21T02:11:00.587 に答える