Jquery: How to clear an element before appending new content?

五迷三道 提交于 2020-03-17 07:43:11

问题


This is my jquery code

 $.ajax({
   url: "PopUpProductDetails.aspx",
            cache: false
     }).done(function (html) {
     $("#dialog").append(html);
 });

The first time, it works just fine. It display the content of the PopUpProductDetails.aspx page. But, after that, If I click again, I get twice the same content, and so forth. I believe the problem is that I need to clear the dialog element first, before appending new content.

How do I do that?


回答1:


.append() appends html to the end of existing html string, use .html() to replace what's currently inside of #dialog.




回答2:


Inside the function clear the dialog first and then fill up with the content

$.ajax({
   url: "PopUpProductDetails.aspx",
            cache: false
     }).done(function (html) {
     $("#dialog").html("");
     $("#dialog").html(html);
 });



回答3:


in case you need to clear the dialog first use .empty() which is faster than .html("")

see Jquery Difference .html("") vs .empty()




回答4:


You can use .empty() first, then use .append() in one line :)

like this:

$.ajax({
  url: "PopUpProductDetails.aspx",
        cache: false
    }).done(function (html) {
    $("#dialog").empty().append(html);
});


来源:https://stackoverflow.com/questions/13822322/jquery-how-to-clear-an-element-before-appending-new-content

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!