parent()。next()。text()返回空字符串

时间:2013-06-30 23:43:11

标签: javascript jquery

您好我有以下使用$.get

动态生成的HTML
<div class="forum-post">
  <div>
    <span class="forum-title">Test post</span><span class="forum-type label label-forum-Discussion">Discussion</span>
  </div>

  <div class="forum-author">
    By: Jared De La Cruz on Thursday, June 27, 2013 7:17:43 PM
  </div>
  <pre>
    This is a test post
  </pre>

  <div class="btn-group">
    <a class="btn btn-mini btn-primary btn-forum-comment" id=""><i class="icon-comment icon-white"></i> comment</a>
  </div>

  <div class="btn-group">
    <a class="btn btn-mini btn-inverse btn-forum-comment-show" id=""><i class="icon-plus-sign icon-white"></i> show</a>
  </div>

  <div class="forum-comments">
    <div class="forum-author">
      By: Jared De La Cruz on Saturday, June 29, 2013 11:56:29 PM
    </div>
    <pre>
      This is a test comment
    </pre>
  </div>
  <hr style="border-top: 1px dotted #b0b0b0;border-bottom: 0px">
</div>

我有以下代码:

// Button dynamic comment show
$("#forum").delegate(".btn-forum-comment-show", "click", function() {
  $(this).parent().next(".forum-comments").toggle();
  console.log($(this).parent().next(".btn-forum-comment-show").context.text);
  console.log($(this).parent().next(".btn-forum-comment-show").text());
  $(this).parent().next(".btn-forum-comment-show").context.text = 'hide';
});

以下代码返回:

show
(an empty string)

我想根据切换操作更改文字。显示/隐藏以及任何想法的图标?先谢谢!

<div class="btn-group">
    <a class="btn btn-mini btn-inverse btn-forum-comment-show" id="51ccf2471238f1cc13000003"><i class="icon-plus-sign icon-white"></i> show</a>
</div>

更新:

<i class="icon-plus-sign icon-white"></i> show应更改为切换<i class="icon-minus-sign icon-white"></i> hide

更新2:这似乎有效。问题是使用.next()而不是.find()

// Button dynamic comment show
$("#forum").delegate(".btn-forum-comment-show", "click", function() {
  $(this).parent().next(".forum-comments").toggle();
  var change = $(this).parent().find(".btn-forum-comment-show").text();
  var show = '<i class="icon-plus-sign icon-white"></i> show';
  var hide = '<i class="icon-minus-sign icon-white"></i> hide';
  if(change == ' show')
  {
    $(this).parent().find(".btn-forum-comment-show").html(hide);
  }
  if(change == ' hide')
  {
    $(this).parent().find(".btn-forum-comment-show").html(show);
  }
});

1 个答案:

答案 0 :(得分:4)

请将next()更改为find()

$(this).parent().find(".btn-forum-comment-show").text("hide");