2014-06-12 160 views
1

我有幾張圖片,當你點擊它們時,我想要一個特定的div文本出現在下面。 這隻適用於第一次點擊出於某種原因。用jQuery替換div內容

滾動內容是放置內容的div。 按摩,禪宗,靈魂是圖像鏈接。 集裝箱分區持有<p></p>信息。

 <section id = "image"> 
    <a href="#" ><img id ="massage"></a>... 
     </section> 
     <section id = "scroll-content"> 
      <div id = "container1"> 
         ... 
        </div> 
      </section> 


$('#massage').click(function() { 

    var htmlString = $('#container2').html(); 

    $('#scroll-content').html(htmlString); 
}); 

$('#zen').click(function() { 

    var htmlString = $('#container1').html(); 
    $('#scroll-content').html(htmlString); 
}); 


$('#soul').click(function() { 

    var htmlString = $('#container3').html(); 
$('#scroll-content').html(htmlString); 
}); 
+3

請分享它的jsfiddle –

+0

的jsfiddle PLS,也就是你的jQuery包裹在一個'$(文件)。就緒()'? –

回答

1

實際工作代碼:

jsFiddle

你舉的例子,因爲當你火指令

$('#scroll-content').html(htmlString); 

你工作不超過一次實際上是覆蓋其中的部分內容

#container1, #container2, [...] 

被存儲。

<section id = "scroll-content"> 
      <div id = "container1"> //You are going to delete me. 
         ... 
        </div> 
    </section> 

您必須更改您的代碼以添加一個虛擬容器。 就象這樣:

<section id = "image"> 
    <a href="#" ><img id ="massage"></a>... 
     </section> 
     <section id = "scroll-content"> 
      <div id = "dummy_container"> 
       ... 
      </div> 
      <div id = "container1"> 
         ... 
        </div> 
      </section> 


$('#massage').click(function() { 

    var htmlString = $('#container2').html(); 

    $('#dummy_container').html(htmlString); 
}); 

$('#zen').click(function() { 

    var htmlString = $('#container1').html(); 
    $('#dummy_container').html(htmlString); 
}); 


$('#soul').click(function() { 

    var htmlString = $('#container3').html(); 
    $('#dummy_container').html(htmlString); 
}); 
1

您正在scroll-content DIV擁有所有containerdiv S和替換HTML後因此迷路,這就是爲什麼它正在爲第一次更換的HTML。

取而代之的是,只要在scroll-content內部顯示/隱藏containerdiv即可。

象下面這樣:

$('#massage').click(function() { 
    $('[id^="container"]').hide(); 
    $('#container2').show(); 
}); 

$('#zen').click(function() { 
    $('[id^="container"]').hide(); 
    $('#container1').show(); 
}); 


$('#soul').click(function() { 

    $('[id^="container"]').hide(); 
    $('#container3').show(); 
}); 
0

如果你想新的內容出現在前面的內容下面,你必須append新的內容。 html()將取代以前的內容。

$('#massage').click(function() { 
    var htmlString = $('#container2').html(); 
    $('#scroll-content').append(htmlString); 
}); 

$('#zen').click(function() { 
    var htmlString = $('#container1').html(); 
    $('#scroll-content').append(htmlString); 
}); 


$('#soul').click(function() { 
    var htmlString = $('#container3').html(); 
    $('#scroll-content').append(htmlString); 
});