为什么这段代码不起作用? [英] why this code isnt working?

查看:56
本文介绍了为什么这段代码不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<!DOCTYPE html>
<html>
<script>

    console.log("hello");
    console.log("Remembertobringanumbrella.");




</script>
<script>

    console.log("this");
</script>

<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

 this is cool
good




</body>
</html>





在我的浏览器中,此代码应打印hello和Remembertobringanumbrella。但是,它只打印这是很酷的好。



有什么想法吗?



In my browser, this code should print hello and Remembertobringanumbrella . But, it only print this is cool good.

Any idea?

推荐答案

要通过JavaScript向网页添加内容,您有两种选择:



document.write();

附加到div或其他元素。



document.write会将文本放在你调用它的任何地方。但是,有些浏览器对使用document.write很敏感,所以它可能并不总是有效。



To add content to a webpage by JavaScript, you have two choices:

document.write();
append to a div or other element.

document.write will put the text wherever you call it. However, some browsers are sensitive about using document.write, so it might not always work.

window.onload = function() {
document.write("hello");
document.write("Remembertobringanumbrella.");
document.write("this");
}





更好的办法是将您的内容附加到页面上已有的div或其他元素:





A better idea is to append your content to a div or other element already on the page:

<html>
<head><title></title></head>
<body>
<div id="myDiv"></div>
<script>
window.onload = function() {
var theElement = document.getElementById("myDiv");
var hello = document.createTextNode("hello");
var remember = document.createTextNode("Remembertobringanumbrella."); 
//'this' is a reserved word in JavaScript
//and cannot be used as a variable name
var final = document.createTextNode("this");

theElement.appendChild(hello);
theElement.appendChild(remember);
theElement.appendChild(final);
}
</script>
</body>
</html>


您需要一个事件来调用您的代码。所有JavaScript都是事件驱动的;换句话说,要执行代码必须要发生一些事情。如窗口加载:





You need an event to invoke your code. All JavaScript is event-driven; in other words, something has to happen for your code to execute. Such as the window loading:


window.onload = function() {
console.log("hello");
console.log("Remembertobringanumbrella.");
console.log("this");
}


使用


这篇关于为什么这段代码不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆