重新加载jquery appendto onclick

时间:2013-09-01 22:09:57

标签: javascript jquery html json

我正在使用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');


        });
};

非常感谢任何帮助!!!

2 个答案:

答案 0 :(得分:1)

我不确定是否会在容器内的现有元素之后追加容器中的新元素。如果您要替换内容,请使用$(element).html(newContent)

答案 1 :(得分:1)

我会让你的结构与众不同。你可以有这样的结构:

<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重新排列到您希望更新内容时显示的位置。

相关问题