jQuery 从 div 中删除 innerHTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2648618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:57:48  来源:igfitidea点击:

Remove innerHTML from div

jquery

提问by PositiveGuy

I'm trying to clear the div's innerHTML before repopulating it. I tried removeData() but once that's called, when I try to add the data, I get nothing from the next line after remove whereas if I remove the removeData() it's fine again. I just want to clear out any previous content in that div before I re-populate it.

我试图在重新填充之前清除 div 的 innerHTML。我尝试了 removeData() 但是一旦调用它,当我尝试添加数据时,删除后我从下一行中什么也没有得到,而如果我删除 removeData() 又好了。我只想在重新填充之前清除该 div 中的任何先前内容。

    divToUpdate.removeData(); //clean out any existing innerHTML div content first
    divToUpdate.html(data);

It looks like it never gets to my divToUpdate.html(data) for some reason after it calls that removeData();

看起来它在调用 removeData() 之后由于某种原因永远不会到达我的 divToUpdate.html(data);

回答by womp

jQuery Data is a different concept than HTML. removeData is not for removing element content, it's for removing data items you've previously stored.

jQuery Data 是一个不同于 HTML 的概念。removeData 不是用于删除元素内容,而是用于删除您之前存储的数据项。

Just do

做就是了

divToUpdate.html("");

or

或者

divToUpdate.empty();

回答by Annika Backstrom

To remove all child elements from your div:

要从 div 中删除所有子元素:

$('#mysweetdiv').empty();

.removeData()and the corresponding .data()function are used to attach data behind an element, say if you wanted to note that a specific list element referred to user ID 25 in your database:

.removeData()并且相应的.data()函数用于在元素后面附加数据,假设您想注意数据库中的特定列表元素引用了用户 ID 25:

var $li = $('<li>Joe</li>').data('id', 25);

回答by Christopher Altman

$('div').html('');

But why are you clearing, divToUpdate.html(data);will completely replace the old HTML.

但你为什么要清除,divToUpdate.html(data);将完全取代旧的HTML。

回答by plodder

divToUpdate.innerHTML =     "";   

回答by James Sumners


var $div = $('#desiredDiv');
$div.contents().remove();
$div.html('<p>This is new HTML.</p>');

That should work just fine.

那应该工作得很好。

回答by matei

you should be able to just overwrite it without removing previous data

你应该能够在不删除以前的数据的情况下覆盖它