简体   繁体   English

使用JavaScript更改div的内容

[英]Change content of a div using JavaScript

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

This should do it: 这应该这样做:

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

And in JavaScript: 在JavaScript中:

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

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

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

Its worth noting that you can also use innerHTML to include other markup. 值得注意的是,您还可以使用innerHTML来包含其他标记。 Also if the DIV des not have an ID you can try using getElementsByTagName . 此外,如果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: 查看原型(下面的链接)(或jQuery)来处理它,因为它们使生活更轻松,特别是当你进入CSS选择器时:

$(document).ready(function(){

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

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

 });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM