javascript - The value output by js does not meet the expectations. I really don't understand it.
迷茫
迷茫 2017-05-19 10:30:26
0
3
654
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

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(3)
PHPzhong

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已经存在
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值发生改变  这个地方就会有输出  
}

</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)

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template