猿问

无法将 setInterval 运行到 javascript 中的另一个函数中

很小的问题...


问题:当我运行代码时,它没有将输入字段值显示到 div 中,但为什么呢?


要求:我的要求是第一个用户在输入字段中输入值,然后当我单击按钮时,输入值将显示在 div 上。


代码:


 function abc(){

            window.setInterval(()=>{

                var myForm = document.getElementById('myForm');

                var text = document.getElementById('text');

    

                text.innerText = myForm.elements['email'].value;

            }, 1);        

        }

<form id="myForm">

            <input type="number" name="email" value="user@example.com">

            <button id="btn" onclick="abc()">click On me</button>

        </form>

        <p id='text'></p>


守着一只汪
浏览 84回答 1
1回答

慕容3067478

您不需要“setInterval”来执行此操作当按钮元素位于表单元素中时,它默认使用发送功能,在本例中该功能会刷新页面。因此,字段的内容一旦被填充就被清理。我删除了表单元素。现在,当单击按钮时,input将获取元素的内容并显示在p元素中<!DOCTYPE html><html><head>&nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0">&nbsp; &nbsp; <title>Document</title></head><body>&nbsp; &nbsp; <input id="mail" type="text" name="email" value="user@example.com">&nbsp; &nbsp; <button id="btn" onclick="abc()">click On me</button>&nbsp; &nbsp; <p id='text'></p>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; function abc() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var mail = document.getElementById('mail');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var text = document.getElementById('text');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; text.innerText = mail.value;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </script></body></html>带 setInterval 的版本按下按钮后“setInterval”将被激活。每 100 毫秒,它就会从输入元素中获取所有信息并将其填充到 P 元素中。您可以在字段中书写,文本将立即出现在另一个元素中。为了在按下按钮后不累积空格,我在代码中设置了一行来停用按钮function abc() {&nbsp; &nbsp; document.getElementById('btn').setAttribute("disabled", true);&nbsp; &nbsp; setInterval(() => {&nbsp; &nbsp; &nbsp; &nbsp; var mail = document.getElementById('mail');&nbsp; &nbsp; &nbsp; &nbsp; var text = document.getElementById('text');&nbsp; &nbsp; &nbsp; &nbsp; text.innerText = mail.value;&nbsp; &nbsp; }, 100);}<input id="mail" type="text" name="email" value="user@example.com"><button id="btn" onclick="abc()">click On me</button><p id='text'></p>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答