2016-02-19 59 views
0

不工作,我想提醒文本框topValue的价值,但解决在()被调用时,一个文本框出现了,但没有文字/价值/数量获得价值在JavaScript

这里是我的代码:

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

function solve() { 
    alert(topValue); 
} 
$('#solveButton').click(function() { 
    solve(); 
}); 

回答

6

该文本框的值首先从DOM中获取。但是,当点击按钮时,会使用相同的缓存值。

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

function solve() { 
    var topValue = document.getElementById('topValue').value 
    alert(topValue); 
} 

注意

$('#solveButton').click(function() { 
    solve(); 
}); 

也可以写成

$('#solveButton').click(solve); 

但是,有一个更好的办法。


我建议你使用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) 
    }); 
}); 
+0

正要说一下使用JQuery一样。不妨使用它,如果它在那里! – Ageonix

0
<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
<script> 


$(document).ready(function() { 

    var topValue = document.getElementById('topValue').value; // have the initial value 

    function solve() { 
     alert(topValue); 
     alert(document.getElementById('topValue').value) // current value 
    } 

    $('#solveButton').click(function() { 
     solve(); 
    }); 

}); 
</script> 
</head> 

<body style="width:50%;"> 
<input type="text" id="topValue" value="ssss"/> 
    <input type="button" value="Solve" id="solveButton" /> 
</body> 

</html>