【问题标题】:jQuery $(this).find and $(this).children not working in this code? if right, tell me reasonjQuery $(this).find 和 $(this).children 在这段代码中不起作用?如果正确,请告诉我原因
【发布时间】:2013-07-28 18:19:18
【问题描述】:
<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) 在数据部分起作用。

【问题讨论】:

    标签: jquery find children


    【解决方案1】:

    这应该可行:

    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')。因此,您可以使用其独特的选择器访问它。

    另外,你的右括号有误,所以我为你更正了。

    【讨论】:

    • 这样做会多次通过选择器。您可以将其存储在一个变量中进行优化,var $pTimeline = $(".privateTimeline"),然后使用该变量。
    【解决方案2】:

    您的上下文在 .success() 回调中发生了变化,因此 this 引用的不是您期望的 jQuery 对象。

    你可以这样做来解决它:

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

    或者:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-28
      • 2014-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-03
      • 2017-06-23
      • 1970-01-01
      相关资源
      最近更新 更多