与onclick事件一起使用时,如何在document.write()函数中添加文本?

时间:2016-04-15 06:27:38

标签: javascript html css

在下面的代码中,document.write()函数无法将字符串作为参数,

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<button type="button" onclick="document.write(5 + 6)">Try it</button>

</body>
</html> 

问题似乎是"document.write(5 + 6)"周围已有引用。

那么如何添加常用的文本字符串呢?

4 个答案:

答案 0 :(得分:3)

尝试使用单引号作为字符串,如下所示:

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<button type="button" onclick="document.write('Hello world')">Try it</button>

</body>
</html>

答案 1 :(得分:1)

你可以这样做 - 让字符串用单引号。

onclick =“document.write('5 + 6')”

注意:您可以插入单引号和双引号。这也有效

onclick ='document.write(“5 + 6”)'

答案 2 :(得分:1)

您最好使用document.getElementById,因为document.writebad practice

<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<p id="result"></p>
<button onclick="document.getElementById('result').innerHTML=5 + 6">Click Me!</button>

答案 3 :(得分:0)

试试这个..               

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<button type="button" onclick='document.write(5 + 6)'>Try it</button>

</body>
</html>