如何在JavaScript中将文本框值处理为变量

时间:2019-07-16 16:45:16

标签: javascript html getelementbyid

我希望能够在文本框中输入内容,然后得到alert来说明输入的内容。容易吧?我尝试使用getElementbyId并为此设置了一些变量,但事实证明它给出了不确定的含义。 这是代码:

    <input type="submit" name="button" style="position: absolute; top: 283.5px; left: 45%; width: 142px; height: 40px; background-color:lime; border-color:forestgreen; font-weight:700; font-family:'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif" value="CLICK ME"/>
    <div style="position: absolute; top: 283.5px; left: 23%; width: 142px; height: 40px; background-color:lime; border-color:forestgreen;">
        <input type="text" name="linksubmit" id="linksubmit" style="position: absolute; top: 10px; width:138px" />
    </div>
    <script>
        var linksubmit = document.getElementById("linksubmit").value 
        function Button() {
            alert(linksubmit)
        }
    </script>

如果您有正当理由无法解决问题,将不胜感激。

2 个答案:

答案 0 :(得分:2)

在调用函数之前,该值仅被捕获一次。您需要更多类似的东西:

        var linksubmit = document.getElementById("linksubmit"); 
        function Button() {
            // Get the value each time the button is pressed, instead of reporting
            // an old, stale value (probably empty string/null/undefined.)
            alert(linksubmit.value);
        }

答案 1 :(得分:1)

const theThing = document.getElementById('testerooni');
showMe = () => { alert(theThing.value) };
<input id="testerooni" type="text">
<button onclick="showMe()">SHOW ME</button>

相关问题