[英]How to get the value property of an element using querySelector
I am a newbie when it comes to JavaScript. 我是JavaScript的新手。 I just made some practice projects to further sharpen my knowledge.
我刚刚进行了一些练习项目,以进一步加深我的知识。
How do i get the value property of and element using ID? 如何使用ID获取和元素的value属性?
This one seems to work : 这似乎工作:
var billAmount = document.getElementById("billamt").value;
But i wanted to use the querySelector method instead of getElementById. 但是我想使用querySelector方法代替getElementById。 Whats the best and proper way to do it?
最佳和正确的方法是什么?
so far i have tried the code below but did not work : 到目前为止,我已经尝试了下面的代码,但是没有用:
var billAmount = document.querySelector("#billamt").value;
const billamt = document.querySelector('#billamt').value; function calculate() { console.log(billamt * 0.25); }
<label>How much did you pay? <input id="billamt" type="text" placeholder="Bill Amount"> </label> <button onclick="calculate()">Calculate</button>
you may view the whole source code of the project via this link : https://codepen.io/anthony-bahinting/pen/dybegMW 您可以通过以下链接查看项目的整个源代码: https : //codepen.io/anthony-bahinting/pen/dybegMW
Your code evaluates the value of #billamt
immediately, no value has been given by the user yet. 您的代码
#billamt
立即评估#billamt
值,而用户尚未提供任何值。 Instead, save a reference to the element and ask for its value when you run your calculate()
method. 而是,保存对元素的引用,并在运行
calculate()
方法时询问其值。
const billamtElem = document.querySelector('#billamt'); // HTMLElement function calculate() { console.log(billamtElem.value * 0.25); }
<label>How much did you pay? <input id="billamt" type="text" placeholder="Bill Amount"> <label> <button onclick="calculate()">Calculate</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.