使用 JavaScript 更改 div 的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2186041/
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-22 23:08:49  来源:igfitidea点击:

Change content of a div using JavaScript

javascripthtml

提问by Rikard

How to dynamically change content of a div using JavaScript?

如何使用 JavaScript 动态更改 div 的内容?

回答by Tatu Ulmanen

This should do it:

这应该这样做:

<div id="foo">Div you want to change</div>

And in JavaScript:

在 JavaScript 中:

document.getElementById('foo').innerHTML = 'Your content';

回答by Carlos Blanco

document.getElementById("divId").innerHTML = "new content!"

document.getElementById("divId").innerHTML = "new content!"

I would recommend using a framework like jQuerythough, because chances are you will be doing more things like this later.

不过我还是建议使用像jQuery这样的框架,因为以后你可能会做更多这样的事情。

回答by donohoe

Its worth noting that you can also use innerHTMLto include other markup. Also if the DIV des not have an ID you can try using getElementsByTagName.

值得注意的是,您还可以使用innerHTML来包含其他标记。此外,如果 DIV des 没有 ID,您可以尝试使用getElementsByTagName

Example, to get the first DIV in the document:

例如,要获取文档中的第一个 DIV:

document.getElementsByTagName("div")[0].innerHTML = "<p>This is a <span>new</span> paragraph</p>";

This allows you to loop through multiple DIVs in the document and check other conditions.

这允许您遍历文档中的多个 DIV 并检查其他条件。

And like they said above, if the DIV has an ID that you know will always be there, then thats better to use:

就像他们上面说的那样,如果 DIV 有一个您知道将永远存在的 ID,那么最好使用:

document.getElementById("theID").innerHTML = "<p>This is a <span>new</span> paragraph</p>";

Check out Prototype (links below) (or jQuery) in handling this as they make life easier, especially when you get into CSS selectors:

查看 Prototype(下面的链接)(或 jQuery)来处理这个问题,因为它们让生活更轻松,尤其是当你进入 CSS 选择器时:

回答by varun

$(document).ready(function(){

$('#btn').click(function(){   

    $('#div_content').load('html.page');

 });
});