更改 JavaScript 中 onkeypress 事件的元素值

问题描述 投票:0回答:2

请帮助我编写脚本。我不明白为什么它不起作用:

<html>
<body>
<input type="text" id="input" onkeypress="myFunction()">
<input type="button" value="Hallo" id="but">
<script>
function myFunction{
    document.getElementById('but').value = "changed";
}
</script>
</body>
</html>
javascript dom-events onkeydown onkeypress
2个回答
2
投票

很简单,您忘记在 myFunction 后面放置括号。

你的代码应该是:

 <script>
function myFunction(){
    document.getElementById('but').value = "changed";
}
</script>

1
投票

这样就可以了。函数需要括号

    function myFunction() {
        document.getElementById('but').value = "changed";
    }
<html>
    <body>
    <input type="text" id="input" onkeypress="myFunction()">
    <input type="button" value="Hallo" id="but">

    </body>
    </html>

另一种方法是

    myFunction = function () {
        document.getElementById('but').value = "changed";
    }
© www.soinside.com 2019 - 2024. All rights reserved.