0

ですから、私はJavaScriptがあまり得意ではありませんが、これが私が行き詰まっていることです。

だから、私はこれを手に入れました:

$(".post-click").click(function()
{
var classid = $(this).attr('id');
var postid = $(this).attr('id');
postid = postid.replace('post-click-id_', '');

alert("ID: " + classid + " PostID: " + postid);

$(this).replaceWith('<img SRC="assets/img/refresh.gif" ALT="" >');

$.post("likepost.php", { postid: postid } , function(data)
{
    if(data.indexOf("Yes") >= 0)
    {
        //Question is about this part
    }
    else
    {
        //Question is about this part
    }

});
});

さて、その「はい」または他の部分で:どうすればそれを行うことができるので、からのデータをに置き換えることができ$(this)ますreplaceWithか?でできると思っていclassidたのですが、どうしたらいいのかよくわかりません。私はこれについて考えました:

$(classid).replaceWith('Yes, yes indeed.');
$(classid).replaceWith('Nope.');

これをどのように機能させますか?

4

2 に答える 2

2

質問を正しく理解し、コールバック内でクリックされた要素を置き換えようとしていると仮定すると$.post、最も簡単な方法は、コールバック外でその要素への参照を維持することです。これにより、すでに一度選択した要素を再選択するためにDOMを再度トラバースする必要がなくなります。

var clicked = $(this);
$.post("likepost.php", { postid: postid } , function(data) {
    if(data.indexOf("Yes") >= 0) {
        clicked.replaceWith("Yes");
    } else {
        clicked.replaceWith("No");
    }
});

属性classidの値を表す文字列であるため、現在の試行は機能しません。idそれからjQueryオブジェクトを作成するには、それを「#」に追加して有効なセレクターを生成する必要があります。

于 2012-10-23T09:24:49.640 に答える
0

持っている要素(のような$("#"+$(this).attr('id')))を見つけるためにIDを使用するのではなく、直接使用してください:$(this)this参照が関数呼び出しから関数呼び出しに変わると(ajaxコールバックでは異なります)、変数にキャッシュする必要があります。

$(".post-click").click(function() {
    var loadImg = $('<img SRC="assets/img/refresh.gif" ALT="" >');
    $(this).replaceWith(loadImg);

    var toReplace = loadImg; // could be $(this) if you hadn't replaced it already

    $.post("likepost.php", { postid: postid } , function(data) {
        toReplace.replaceWith( data.indexOf("Yes") >= 0
           ? "success"
           : "failed"
        );
    });
});
于 2012-10-23T09:28:52.753 に答える