2012-12-30 89 views
1

我试图增加一个<span>的html值,当一个按钮被点击,但jQuery的说,<span>的值是未定义的,即使有一个身体的数字显示在页面上。下面是生成HTML PHP部分:是应该魔法了HTMLjQuery的 - <span>的html返回'undefined'

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>' 

,这里是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而不是实际的数字。任何人都可以解释一下这个问题吗?

感谢

回答

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 { 
      }; 
     } 
    }); 
}); 
+0

它的工作原理,谢谢! – Taimur

+0

您可以使用ajax对象内的上下文选项。 {url:...,context:this} – Trevor

+2

将'jQuery'对象加上'$'前缀也是一个好习惯。所以'$ clicked' – Trevor

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 { 
        } 
     } 
    }); 
}); 
+0

或者使用上下文选项来传递'this'' – Trevor

1

我认为$(this)这里没有引用您的DOM元素。 Ajax的功能之前尝试加入

var elem = $('.upvote'); 

而在AJAX功能使用

elem而非$(this)

+0

或者使用'context'选项来传递'this'' – Trevor

+0

哦,@Trevor这听起来像是我需要学习的东西。请你可以编辑我的答案吗? - 或提供你自己的,我会投票。 –

+0

我贴了:) .. – Trevor

1

thiscontext为它的方法应用到ajax

没有必要做出新的变种访问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 
       } 
      } 
     }); 
    }); 
+0

谢谢,这应该证明有帮助。 –