下面是简单的代码。当我单击按钮时,将调用 javascript 函数 myFunction,并将变量 str 设置为字符串 test。最后,将变量 str 中存储的值设置为 id 属性等于 demo 的文本字段,并在文本字段中显示该字符串。
但是,实际上,当我单击“Click Me”按钮时,什么也没有发生。您可以在浏览器中尝试一下。有人可以告诉我如何修改代码,以便在单击“Click Me”按钮时文本“test”出现在文本字段中。
谢谢
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(str)
{
$('#demo').val(str);
}
</script>
</head>
<body>
<p>Testing...</p>
<button onclick="myFunction("test")">Click me</button>
<input type="text" id="demo" />
</body>
</html>
最佳答案
更改为:
onclick='myFunction("test")'
也这样做:
function myFunction(str) {
document.getElementById('demo').value = str;
}
与.querySelectorAll()
document.querySelectorAll('#demo').value = str;
<小时/>
双引号的实现很糟糕,要么用单引号括起来,要么转义内部引号。
注意:
您尚未使用 jQuery 库,因此仍然无法按您的预期工作,因此您可以选择也加载 jQuery 库或使用 native javascript。
<小时/>最好保持低调:
首先执行以下操作:
<button id="btn">Click me</button>
然后这个脚本:
function myFunction(str) {
document.getElementById('demo').value = str;
}
document.getElementById('btn').onclick = function(){
myFunction('test');
};
关于Javascript onclick 事件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24014448/