2010-04-18 38 views
2

我遇到麻烦以下jQuery脚本才能正常工作 - 它的功能如下:在jQuery中克隆选择器及其所有子项?

1)隐藏每个标题

2)一旦点击标题下面的内容,替换为“#first “标题”+标题下的隐藏内容。

我只能看到脚本将标题本身克隆到#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

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

1

您还需要显示隐藏的元素。请注意,replaceWith会返回已移除的元素,因此您需要为新的“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; 
}); 
+0

谢谢!修正了这个问题:)出于好奇,为什么不是$('#first-post).show();足够?为什么我们需要首先找到隐藏的选择器? – 2010-04-18 21:47:41

+1

@HipHop:因为它不是隐藏的#首篇文章元素。在元素上调用“show”不会显示隐藏的子项。 – Guffa 2010-04-18 21:50:27