如何使用javascript和html更正此代码。提前致谢! 请帮我解决这个问题。
<input type="text" id="text1">
<input type="text" id="text2">
<input type="submit" onclick="submit()">
<script type="text/javascript">
function submit() {
var q = document.getElementById('text1');
var w = document.getElementById('text2');
if (q > w) {
console.log('q is greaterthan in w');
} else{
console.log('q is less that in w');
}
}
</script>
答案 0 :(得分:-2)
您必须获得输入的值,如下所示:document.getElementById('text1').value
function submit() {
var q = document.getElementById('text1').value;
var w = document.getElementById('text2').value;
if (q > w) {
console.log('q is greaterthan in w');
}
else
{
console.log('q is less that in w');
}
}
答案 1 :(得分:-2)
您正在比较DOM元素(输入字段)本身,而不是它们的值。为了获取值并进行比较,您必须实际获取.value
属性并将它们视为数字(浮点数或整数或其他任何内容)。
function submit() {
var q = parseFloat(document.getElementById('text1').value);
var w = parseFloat(document.getElementById('text2').value);
if (q > w) {
console.log('q is greater than w');
}
else
{
console.log('q is less or equal than w');
}
}
<input type="text" id="text1">
<input type="text" id="text2">
<input type="submit" onclick="submit()">