从文本框中获取不在JavaScript中工作的价值

ige*_*lot 0 html javascript css jquery

我想提醒文本框topValue的值,但是当调用solve()时,会出现一个文本框,但是没有文本/值/数字

这是我的代码:

var topValue = document.getElementById('topValue').value

function solve() {
    alert(topValue);
}
$('#solveButton').click(function () {
    solve();
});
Run Code Online (Sandbox Code Playgroud)

Tus*_*har 6

首先从DOM获取文本框的值.但是,单击按钮时,将使用相同的缓存值.

这可以通过在函数中移动从DOM读取值的语句来解决.

function solve() {
    var topValue = document.getElementById('topValue').value
    alert(topValue);
}
Run Code Online (Sandbox Code Playgroud)

注意

$('#solveButton').click(function () {
    solve();
});
Run Code Online (Sandbox Code Playgroud)

也可以写成

$('#solveButton').click(solve);
Run Code Online (Sandbox Code Playgroud)

但是,有一种更好的方法.


我建议你使用jQuery从文本框中获取值.

// When DOM is completely loaded
$(document).ready(function () {
    // On click of the `solveButton`
    $('#solveButton').click(function () {

        // Get the value of the `#topValue`
        var topValue = $('#topValue').val();

        // For debugging use `console.log` instead of `alert`
        console.log('topValue', topValue)
    });
});
Run Code Online (Sandbox Code Playgroud)