[英]Replace div content with JQuery
我有一些圖像,當您單擊它們時,希望在其下方顯示特定的div文本。 由於某些原因,這僅在首次點擊時有效。
scroll-content是放置內容的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 );
});
您正在替換具有所有container
div
的scroll-content
div下的html,因此在替換html后迷路了,這就是為什么它第一次起作用。
取而代之的是,僅使show / hide container
div
s位於scroll-content
內部。
像下面這樣:
$('#massage').click(function() {
$('[id^="container"]').hide();
$('#container2').show();
});
$('#zen').click(function() {
$('[id^="container"]').hide();
$('#container1').show();
});
$('#soul').click(function() {
$('[id^="container"]').hide();
$('#container3').show();
});
實際工作代碼:
您的示例無法正常運行超過一次,因為您觸發指令時
$('#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);
});
如果希望新內容顯示在先前內容的下面,則必須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 );
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.