我试图通过在JS中用.TextContent覆盖HTML来显示消息Hey friends。所以不要只是说嘿!我想要它说嘿朋友!
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>friends</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<!-- This links to the js code specific for this page -->
<script src="multiwrites.js"></script>
<script src="multiwrites2.js"></script>
</head>
<body>
<div id="title">Hey!</div>
</body>
</html>
的Javascript
var message;
message = 'Hey Friends';
var elName = document.getElementById('title');
elName.textContent = message;
答案 0 :(得分:2)
您需要在他们将访问的DOM节点之后包含您的脚本标记:
<!DOCTYPE html>
<html>
<head>
<title>Friends</title>
</head>
<body>
<div id="title">hello</div>
<script type="text/javascript">
var el = document.getElementById('title');
el.textContent = "hello world";
</script>
</body>
</html>
或等待DOM准备就绪&#34;,我可以看到你已经包含了jQuery,所以可以用:
jQuery(function($) {
// In here the whole DOM will be "ready"
// Using jQuery API instead of native DOM API.
$('#title').text('hello world');
});