获取输入值并显示在另一个 div 中

Mat*_*zle 1 html javascript jquery

我一生都无法弄清楚为什么以下内容不起作用。我从这里的 W3school 示例中获取了 if 。

基本上我想在输入文本更改时从输入文本中获取值并修改另一个 div 以包含该值。我只希望 div 显示新值,但我确实希望它每次都改变它,所以我认为 onchange 是要走的路。

    <!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
var div = document.getElementById('divID');
div.innerHTML = div.innerHTML + x.value;
}
</script>
</head>
<body>

Enter your name: <input type="text" id="fname" onchange="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>

<div id="divID"></div>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

在此先感谢您对这一问题的所有帮助。

Cha*_*cho 5

您有两个问题,首先是 x 未定义。其次,您应该为此使用另一个触发器,以便每次都发生这种情况。

试试这个:

    function myFunction()
    {
        var input = document.getElementById('fname')
        var div = document.getElementById('divID');
        div.innerHTML = div.innerHTML + input.value;
    }
Run Code Online (Sandbox Code Playgroud)

并将您的 html 更改为:

<input type="text" id="fname" onkeypress="myFunction()">
Run Code Online (Sandbox Code Playgroud)