开发者

XML to JQUERY, displays data, but loops contents

I have some jquery code that loads the contents of a XML file generated by a JSP Servlet.

The idea is it pulls the information and then displays it, whilst ref开发者_开发问答reshing every 1 sec.

The problem i have, is every time it refreshes it just adds the data back onto the old data, so it just loops out the same values:

Here is my code:

    <script>


        $(document).ready(function() {




        });
    </script>

How can i get it to display once, then when it refreshes it, clears its self.

Thanks


Replace your line $('#tidm').append($(html)); with $('#tidm').empty().append($(html));


call:

$('#tidm').html(''); // .empty() is slightly faster

before your each loop, this will clear the old HTML

Edit: My initial answer was just to clear the html but some of the comments point out valid performance issues in the code from the original question. So, while the performance of the original code wasn't subject of the question I'm going to update my answer with what I believe would be more performant.

I havent tested this but the intention should be clear.

$(document).ready(function() {
    var $tidm = $('#tidm');
    var html;
    setInterval(function() {
        $.get('Stocks', function(data) {
            html = '';
            $tidm.empty(); // using empty instead of .html('') as suggested
            $(data).find('stock').each(function() {
                var $stock = $(this);
                var tidm = $stock.find("tidm").text();
                var name = $stock.find("name").text();
                var price = $stock.find("price").text();
                var change = $stock.find("change").text();
                html += '<p>tidm = ' + tidm + '</p>';
                html += '<p>name =' + name + '</p>';
                html += '<p>price = ' + price + '</p>';
                html += '<p>change = ' + change + '</p>';
            });
            $tidm.html(html);
        });
    }, 1000); // 1000 milliseconds = 1 second.
});

If there are any other improvements that could be made or mistakes I've made let me know in the comments.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜