在下面的代码中,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)"
周围已有引用。
那么如何添加常用的文本字符串呢?
答案 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.write
是bad 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>