[英]Why is this Javascript code not writing to the webpage?
I have just started learning Javascript. 我刚刚开始学习Javascript。 I want "Hello World!"
我想要“ Hello World!” to be written to a webpage once a user clicks a button.
用户单击按钮后将其写入网页。 I have tried this:
我已经试过了:
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
document.write("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" />
</form>
</body>
</html>
I can get it to do a window.alert("Hello World!")
but not do document.write("Hello World!")
for some reason. 由于某种原因,我可以使它执行
window.alert("Hello World!")
但不能执行document.write("Hello World!")
。 What happens is the button disappears and no text is displayed. 发生的情况是按钮消失并且没有文本显示。 My guess is that the problem is in the
document.write
but I do not know how to work around it. 我的猜测是问题出在
document.write
但我不知道如何解决。 Any suggestions? 有什么建议么?
Because the document has already been written at that point. 因为那时文档已经写好了。 You can set text like so:
您可以这样设置文本:
<button id="lol">blah</button>
<script>
function setText( obj, to ) {
obj.textContent? obj.textContent = to : obj.innerText = to;
}
var lol = document.getElementById('lol')
lol.onclick = function() {
var p = document.createElement('p');
document.body.appendChild(p);
setText( p, 'hi' );
}
</script>
Another popular but often looked down technique would be innerHTML
. 另一种流行但经常被忽视的技术是
innerHTML
。
Document.write is used to write to the currently loading HTML file. Document.write用于写入当前正在加载的HTML文件。 Once the page has been loaded, and a user begins interacting with the page, document.write is useless.
一旦页面被加载,并且用户开始与页面进行交互,document.write就没有用了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.