var number1 = document.getElementById("queue");
height1 = number1.value+("px");
queue is an input box, number1.value is its input value (a number), but the output of height1 is always px without any number.
for example:
console.log(number1.value); //20
console.log(height1);//px
I also tried a method
var number1 = document.getElementById("queue");
var number1Value = number1.value;
height1 = number1Value+("px");
This time it’s even weirder,
console.log(number1.value);//20
console.log(number1Value);//
console.log(number1.value.constructor == String);//true
Proofnumber1.value
is a string, then string plus string should be OK
業(yè)精于勤,荒于嬉;行成于思,毀于隨。
1. Probably what you understand
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" id="input">
</body>
<script>
var val=document.getElementById("input");
var height=val.value+"px";//你這個地方 定義height的時候 val.value并不存在
console.log(height)//px
</script>
</html>
2. The correct way to obtain it
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" id="input" value="20">
</body>
<script>
var val=document.getElementById("input");
var height=val.value+"px";//你這個地方 定義height的時候 val.value已經(jīng)存在
console.log(height)//20px
</script>
</html>
3. Another way to monitor the content in the input box
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" id="input" onchange="getVal()">
</body>
<script>
var val=document.getElementById("input");
function getVal() {
var height=val.value+"px";
console.log(height)//這種只要input值發(fā)生改變 這個地方就會有輸出
}
</script>
</html>
You are executing it when you open the page. The function is only executed once. When you enter the value again, you do not execute the method, and the first time the value is empty!
You need an event handling function. When the page is just loaded, the value must be empty, because you have not written a value in the input yet
var height = 0;
var input = document.querySelector('#input');
var btn = document.querySelector('#btn');
btn.addEventListener('click', function(){
var value = input.value;
height = value + 'px';
}, false)