jQuery $(this).find 和 $(this).children 在此代码中不起作用?如果对,告诉我原因


<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
var commentUrl = 'comment.jsp';
$('.privateTimeline').click(function() {
 $.ajax({
 url: commentUrl,
 type:'post',
  data:{
       no : $(this).find('.no').text()  // working!
 },
 success:function(data){
    if( $(this).children('.comment').is(':hidden') ) {  // not working!
    $(this).find('.comment').slideDown(400);  // not working!
    $(this).find('.comment').html(data);   // not working!
 }
 else {
    $(this).find('.comment').slidUp(400);  // not working!
  }
 });
})
</script>
  1. 我不知道这个代码不起作用的原因。
  2. 我想选择privateTimeline的子类节点,所以做事件。
  3. 不在成功功能部分工作,但 $(this( 在数据部分工作。

这应该有效:

var $target =$('.privateTimeline');
$target.click(function() {
    $.ajax({
        url: commentUrl,
        type:'post',
        data:{
            no : $(this).find('.no').text()  // working!
        },
        success:function(data){
           if( $target.children('.comment').is(':hidden') ) {  // not working!
               $target.find('.comment').slideDown(400);  // not working!
               $target.find('.comment').html(data);   // not working!
            }
            else {
                $target.find('.comment').slidUp(400);  // not working!
             }
        }
    });
});

success:function(data){}中,$(this)不再指向$('.privateTimeline')。因此,您可以使用其唯一的选择器访问它。

另外,你的右括号错了,所以我为你纠正了。

你的上下文在.success()回调中发生了变化,所以this引用了你期望的jQuery对象以外的内容。

你可以做这样的事情来解决它:

var _this = this;
...
, success(function(){
    $(_this).find(".yourClass").yourFunc()
});

或:

...
, success((function() {
    $(this).find(".yourClass").yourFunc();
}).bind(this));

相关内容

最新更新