在jQuery中克隆一个选择器+它的所有子节点?

时间:2010-04-18 21:32:04

标签: jquery jquery-selectors

我无法让以下JQuery脚本正常运行 - 其功能如下:

1)隐藏每个标题下面的内容

2)点击标题后,将“#first-post”替换为标题+标题下方的隐藏内容。

我似乎只能让脚本将标题本身克隆为#first-post,而不是标题+下面的内容。知道为什么吗?

<HTML>
<HEAD>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</HEAD>
<script>
$(document).ready(
function(){ 
$('.title').siblings().hide();
$('.title').click( function() {
$('#first-post').replaceWith($(this).closest(".comment").clone().attr('id','first-post'));
$('html, body').animate({scrollTop:0}, 'fast');
return false;
});
});
</script>
<BODY>
<div id="first-post"> 
  <div class="content"><p>This is a test discussion topic</p> </div> 
</div>
<div class="comment"> 
<h2 class="title"><a href="#1">1st Post</a></h2> 
  <div class="content">
    <p>this is 1st reply to the original post</p> 
  </div> 
  <div class="test">1st post second line</div>
  </div>
<div class="comment"> 
<h2 class="title"><a href="#2">2nd Post</a></h2> 
  <div class="content"> 
    <p>this is 2nd reply to the original post</p> 
      </div> 
  <div class="test">2nd post second line</div>
  </div> 
</div>
<div class="comment"> 
<h2 class="title"><a href="#3">3rd Post</a></h2> 
  <div class="content"> 
    <p>this is 3rd reply to the original post</p> 
  </div> 
  <div class="test">3rd post second line</div>
    </div> 

</div>

</BODY>
</HTML>

2 个答案:

答案 0 :(得分:2)

您正在克隆隐藏的元素,因此副本也会被隐藏。在那里添加对show()的电话。

答案 1 :(得分:1)

您还需要显示隐藏的元素。请注意,replaceWith返回已删除的元素,因此您需要在执行show时重新查询新的“first-post”元素,然后是隐藏的后代。

$('.title').click( function() {
    $('#first-post').replaceWith($(this).closest(".comment").clone().attr('id','first-post'));
    $('#first-post').find(':hidden')
                   .show();
    $('html, body').animate({scrollTop:0}, 'fast');
    return false;
});
相关问题