2010-04-18 39 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