如何使用onkeyup在标签内显示用户输入值

我想知道如何使用 onkeyup 方法将文本框中输入的值显示到标签中。我可以将其显示在文本框中。这就是我到目前为止所做的:


<script>

    function multiply(value){

        var x;

        x= 2*value;

        document.getElementById('out2x').value=x;

    }

</script>


<body>

  <div style="margin:auto; width:300px; background-color:lightblue; padding:5px;">

    <label for="">Input</label>

    <input type="text" name="" onkeyup="multiply(this.value);">

    <br>


    <label for="">Result(x2):</label>

    <input type="text" id="out2x" name="" readonly>


  </div>


</body>

我尝试将 id 'out2x' 设置为标签,但它不起作用。


千万里不及你
浏览 122回答 2
2回答

catspeake

在你的例子中,我有一个像这样的带有 jQuery 的简单 Keyup$('#value').keyup(function (){&nbsp; &nbsp; $('#copy-value').val($(this).val());});例如这个片段:$('#value').keyup(function (){&nbsp; &nbsp; $('#copy-value').val($(this).val());});<body><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>&nbsp; <div style="margin:auto; width:300px; background-color:lightblue; padding:5px;">&nbsp; &nbsp; <label for="">Input</label>&nbsp; &nbsp; <input id="value" type="text" name="">&nbsp; &nbsp; <br>&nbsp; &nbsp; <label for="">Result(x2):</label>&nbsp; &nbsp; <input id="copy-value" type="text" name="" readonly>&nbsp; </div></body>

慕娘9325324

script您实际上在文档中的哪里有?它应该位于 CLOSINGbody标记之前,这样当到达它时,所有 HTML 都将被解析。如果在script解析 HTML 之前运行,您的document.getElementById()语句将找不到匹配的元素。此外,thevalue始终input是一个字符串。您必须将其转换为数字才能使用它进行数学运算。有多种方法可以做到这一点,您需要为输入错误地包含非数字值的情况做好准备,但在下面,我通过在其前面添加 a 来转换value它+。还有一些其他的事情......您没有label正确使用该元素。该for属性的值必须与id标签为“for”的表单元素的属性值相匹配,或者您可以将表单元素嵌套在 中,label以便它知道它与哪个元素相关。不要使用内联 JavaScript - 将其分离到 JavaScript 代码中。<body>&nbsp; <div style="margin:auto; width:300px; background-color:lightblue; padding:5px;">&nbsp; &nbsp; <label>Input&nbsp; &nbsp; &nbsp; <input type="text">&nbsp; &nbsp; </label>&nbsp; &nbsp; <br>&nbsp; &nbsp; <!-- Not always best to use an input for output. -->&nbsp; &nbsp; <span>Result(x2):&nbsp; &nbsp; &nbsp; <span id="out2x"></span>&nbsp; &nbsp; </span>&nbsp; </div>&nbsp;&nbsp;&nbsp; <!-- Place your script just before the closing body tag&nbsp; &nbsp; &nbsp; &nbsp;so that by the time it's reached, all the HTML elements&nbsp; &nbsp; &nbsp; &nbsp;will have been parsed. -->&nbsp; <script>&nbsp; &nbsp; // Do your event handling in JavaScript, not with inline JavaScript&nbsp; &nbsp; document.querySelector("input").addEventListener("keyup", function(event){&nbsp; &nbsp; &nbsp; // You must convert the input string to a number&nbsp; &nbsp; &nbsp; document.getElementById('out2x').textContent = 2* +this.value;&nbsp; &nbsp; });&nbsp; </script></body>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript