1

我试图在<span>单击按钮时增加 a 的 html 值,但 jQuery 说 a 的值<span>是未定义的,即使页面上实际显示了一个数字。这是生成 HTML 的 PHP 部分:

echo '<div class="box" style="background-color:'.$colours[0].'">
      <p>'.$confessions[0].'<br></p><br>
      <div class="overlay"></div>
      <div class="slide">
        <div class="slideleft">#'.$ids[0].'</div>
        <div class="slideright">
            <span class="upvote" id="'.$ids[0].'">Upvote</span>
            <span class="counter" id="'.$ids[0].'">"'.$counter[0].'"</span>
        </div>
      </div>
      </div>'

这是应该使 HTML 变魔术的 jQuery:

$("body").on("click", ".upvote", function(e) {
    $.ajax({
        url: 'vote.php',
        data: {
            type: 'up',
            id: $(this).attr('id')
        },
        type: 'post',
        success: function(data) {
            if (data == 'ok') {
                alert($(this).next().html());
            } else {};
        }
    });
});

按下按钮时它确实会发出警报upvote,但它的值undefined与实际数字相反。任何人都可以对这个问题有所了解吗?

谢谢

4

4 回答 4

6

$(this)将不再包含单击的元素,因为它在您的成功函数中超出范围,相反,您需要缓存该变量以在您的成功函数中使用。

例如:

$("body").on("click", ".upvote", function(e){
    var clicked = $(this);
    $.ajax({ 
        url: 'vote.php',
        data: { type: 'up', id: clicked.attr('id') },
        type: 'post',
        success: function(data) {
            if(data == 'ok'){
                alert(clicked.next().html());
            } else {
            };
        }
    });   
});
于 2012-12-30T16:11:25.590 回答
1

你的问题是这this不是你所期望的;在“成功”回调中,this已被反弹到jqXHR对象 - 并且得到它next()的是返回未定义的内容。

我建议显式捕获来解决这个问题:

$("body").on("click", ".upvote", function(e){
    var self = this; /// capture "this" explicitly here
    $.ajax({ 
        url: 'vote.php',
        data: { type: 'up', id: $(this).attr('id') },
        type: 'post',
        success: function(data) {
                    if(data == 'ok'){
                    alert($(self).next().html()); /// so now it is available here
                  } else {
                  }
        }
    });   
});
于 2012-12-30T16:13:15.513 回答
1

我认为这$(this)不是在这里引用您的 DOM 元素。在ajax函数之前尝试添加

var elem = $('.upvote');

并使用

elem而不是$(this)在ajax函数中。

于 2012-12-30T16:14:02.360 回答
1

传递thiscontext它以应用于方法中ajax

无需创建新的 var 即可访问this

查看文档:http ://api.jquery.com/jQuery.ajax/

 $("body").on("click", ".upvote", function(e){

        $.ajax({ 
            url: 'vote.php',
            context: this, // capture this here instead
            data: { type: 'up', id: $(this).attr('id') },
            type: 'post',
            success: function(data) {
                if(data == 'ok'){
                    alert($(this).next().html()); /// so now it is available here
                } 
            }
        });   
    });
于 2012-12-30T17:10:48.847 回答