如何在不覆盖 javascript 中的所有其他内容的情况下向文档动态添加段落?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6407122/
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
How can I dynamically add a paragraph to a document without overwriting everything else in javascript?
提问by luke
I'm just learning how to write javascript, but i've already learned java. the difference in syntax is driving me nuts. i'm just doing a dumb little sample code to see if i can add a paragraph to the end of a page at the click of a button. but i can't seem to do it. i'm positive that i'm really close to achieving my goal though. i already know the button functions properly. there is a similar post that has helped me, but i can't seem to quite get to where i want. here's the javascript:
我只是在学习如何编写 javascript,但我已经学习了 java。语法上的差异让我发疯。我只是在做一个愚蠢的小示例代码,看看我是否可以通过单击按钮在页面末尾添加一个段落。但我似乎做不到。我很确定我真的很接近实现我的目标。我已经知道按钮功能正常。有一个类似的帖子对我有帮助,但我似乎无法到达我想要的地方。这是javascript:
function displayDate()
{
//object that will hold newParagraph
var iframe = document.createElement("iframe");
iframe.width = 400;
iframe.height += 50;
iframe.id ="iframe";
var comment = "woohooo! go me.";
//var doc = iframe.contentDocument || iframe.document;
var newParagraph = document.createElement('p');
newParagraph.textContent = comment;
//doc.body.appendChild(newParagraph);
iframe.appendChild(newParagraph);
document.getElementById("updateDiv").appendChild(iframe);
//the id updateDiv is in my html
}
the iframe shows up as a blank box without the text. i cannot figure out how to get the text to appear in the iframe.
iframe 显示为一个没有文本的空白框。我不知道如何让文本出现在 iframe 中。
here's the similar post if you're curious: Adding iframe and paragraph elements dynamically
如果您好奇,这里是类似的帖子:动态添加 iframe 和段落元素
回答by devoid
If you just want to add a paragraph to the document, ditch the iframe. An iframeembeds a completely new document inside your browser window. For your purposes, simply appending the <p>
element onto the <div id='updateDiv'>
should be enough:
如果您只想在文档中添加一个段落,请放弃 iframe。一个iframe中嵌入浏览器窗口中一个完全新的文档。出于您的目的,只需将<p>
元素附加到<div id='updateDiv'>
就足够了:
function displayDate() {
var comment = "woohooo! go me.";
var newParagraph = document.createElement('p');
newParagraph.textContent = comment;
document.getElementById("updateDiv").appendChild(newParagraph);
}
and here's the HTML:
这是 HTML:
<button id='a'>Click Me!</button>
<div id='updateDiv'></div>
And here's the fiddle example: http://jsfiddle.net/MYy72/
这是小提琴示例:http: //jsfiddle.net/MYy72/