Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript属性(';id';)和_Javascript_Jquery - Fatal编程技术网

JavaScript属性(';id';)和

JavaScript属性(';id';)和,javascript,jquery,Javascript,Jquery,所以我对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).

所以我对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
    }

});
});

我将如何实现这一点?

假设我正确理解了问题,并且您正在尝试替换
$回调中单击的元素。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对象,您需要将它附加到“#”以生成有效的选择器。

不要使用id来查找您刚刚拥有的元素(如
$(“#“+$(this).attr('id'))
),而是直接使用它:
$(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"
        );
    });
});
$(“.post click”)。单击(函数(){
var loadImg=$('');
$(this).replacetwith(loadImg);
var toReplace=loadImg;//如果您还没有替换它,它可能是$(this)
$.post(“likepost.php”,{postid:postid},函数(数据){
toReplace.replaceWith(data.indexOf(“Yes”)>=0
“成功”
:“失败”
);
});
});

对于这些类型的问题,如果您创建一个JSFIDLE,它将非常有帮助。
$(".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"
        );
    });
});