开发者

jQuery .html() method seems to overwrite containing element

开发者 https://www.devze.com 2022-12-28 10:31 出处:网络
I\'m writing an AJAX function that returns some information to display in a <div>. My code looks like this:

I'm writing an AJAX function that returns some information to display in a <div>. My code looks like this:

HTML:

<div id="basket_summary">Your 开发者_如何学Gobasket's empty. Why not add some items to get started?</div>

jQuery (relevant part of ajax call):

success: function(products){
    $('#basket').html(products.basket);
    $('#basket_summary').html(products.summary);

I can confirm that the products.summary variable contains the text I want to display.

When I run this code for the first time, it works, but then when I check the source, the <div id="basket_summary"> part is removed, so the second time I call the function, the element doesn't exist anymore. If I include <div id="basket_summary"> in my AJAX return data, it adds it, so I end up with this:

<div id="basket_summary">
    <div id="basket_summary">3 items in your basket</div>
</div>

This isn't how the function normally works for me - it doesn't ordinarily touch the containing element. Can anybody figure this out?


I'm guessing that the basket_summary div is inside of the basket div, like this:

<div id="basket">
   <div id="basket_summary">
   </div>
</div>

If this is the case, when you use this line...

$('#basket').html(products.basket);

...it will erase everything inside of the basket div and replace it with whatever is in products.basket. You might need to use .prepend() or .append() instead of html().

0

精彩评论

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