我目前正在使用jquery appendTo将照片和文本加载到div中。我试图做到这一点,以便在每次单击时,它都只是重新加载要添加的内容,但是它只是继续添加新元素,而不是清除旧元素并加载新元素。我的功能目前看起来像这样:
function load_new() {
$.getJSON('images.json', function(data) {
var $item = data.images[Math.floor(Math.random()*data.images.length)];
var $image = $('<script id="scripty"> $.backstretch("' + $item.image + '", {speed: 1200}); </script>');
var $caption = $('<h1>' + $item.caption + '</h1>');
$image.appendTo('body');
$caption.appendTo('.text');
});
};
任何帮助是极大的赞赏!!!
最佳答案
我会让您的结构有所不同。您可能具有以下结构:
<body>
<div id="image"></div>
<div class="text">
<div class="append-text"></div>
</div>
</body>
然后您的函数可以看起来像这样:
function load_new() {
$.getJSON('images.json', function(data) {
var $item = data.images[Math.floor(Math.random()*data.images.length)];
var $image = $('<script id="scripty"> $.backstretch("' + $item.image + '", {speed: 1200}); </script>');
var $caption = $('<h1>' + $item.caption + '</h1>');
$('#image').html($image);
$('.append-text').html($caption);
}
然后只需将div重新排列到更新内容时希望其显示的位置即可。