我试图将html代码块替换为另一个html块。但我不能这样做。
这是html块
<div id="book1">
<div class="page1" style="background: url(modules/mod_test/tmpl/img/new/1.jpg); width:100%;"></div>
<div class="page2" style="background: url(modules/mod_test/tmpl/img/new/2.jpg); width:100%;"></div>
<div class="page3" style="background: url(modules/mod_test/tmpl/img/new/3.jpg); width:100%;"></div>
<div class="page4" style="background: url(modules/mod_test/tmpl/img/new/4.jpg); width:100%;"></div>
</div>
使用此代码块
<div id="book2">
<div class="page1" style="background: url(modules/mod_test/tmpl/img/new/new1.jpg); width:100%;"></div>
<div class="page2" style="background: url(modules/mod_test/tmpl/img/new/new2.jpg); width:100%;"></div>
<div class="page3" style="background: url(modules/mod_test/tmpl/img/new/new3.jpg); width:100%;"></div>
<div class="page4" style="background: url(modules/mod_test/tmpl/img/new/new4.jpg); width:100%;"></div>
</div>
我尝试使用此代码,但它无法正常工作
$(document).ready(function() {
$('.test-img').click(function () {
var lookbook2 = '<div class="page1" style="background: url(../images/book2/new1.jpg); width:100%;"></div>' + '<div class="page1" style="background: url(../images/book2/new2.jpg); width:100%;"></div>';
$('#book1').append(lookbook2);
});
任何人都可以帮助我吗?
答案 0 :(得分:0)
试试这个:
$(document).ready(function() {
$('.test-img').click(function() {
//save book2 html content
var lookbook2 = $('#book2').html();
//replace book2 html content with book1 html content
$('#book2').html($('#book1').html());
//replace book1 html content with the saved book2 html content
$('#book1').html(lookbook2);
});
}
答案 1 :(得分:0)
要替换整个块使用:
$(document).ready(function() {
$('.test-img').click(function() {
var lookbook2 = '<div id="book2"><div class="page1" style="background: url(../images/book2/new1.jpg); width:100%;"></div>'+'<div class="page1" style="background: url(../images/book2/new2.jpg); width:100%;"></div></div>';
$('#book1').replaceWith(lookbook2);
});
});
要仅替换内容(保持div和ID相同),请使用:
$(document).ready(function() {
$('.test-img').click(function() {
var lookbook2 = '<div class="page1" style="background: url(../images/book2/new1.jpg); width:100%;"></div>'+'<div class="page1" style="background: url(../images/book2/new2.jpg); width:100%;"></div>';
$('#book1').html(lookbook2);
});
});
替换内容的示例:http://jsfiddle.net/c5zzuymn/1/
答案 2 :(得分:0)
从你的代码中我假设你想用div#book2 替换div#book1点击带有类test-img的元素
试试这个:
$(document).ready(function() {
$('.test-img').click(function() {
var lookbook2 = '<div id="book2"><div class="page1" style="background: url(modules/mod_test/tmpl/img/new/new1.jpg); width:100%;"></div><div class="page2" style="background: url(modules/mod_test/tmpl/img/new/new2.jpg); width:100%;"></div><div class="page3" style="background: url(modules/mod_test/tmpl/img/new/new3.jpg); width:100%;"></div><div class="page4" style="background: url(modules/mod_test/tmpl/img/new/new4.jpg); width:100%;"></div></div>';
$('#book1').after(lookbook2);
$('#book1').remove();
});
}