繁体   English   中英

在 Javascript 中单击按钮后更改变量值

[英]change variable value once a button has been clicked in Javascript

我想要做的是能够在单击 btn-here 后更改 val 的值。 我有以下代码,但它不起作用。 我错过了什么?

    var btn = document.getElementById('btn-here');
    var val = document.getElementById('text-here').value;
    btn.addEventListener("click", () => {
    var val = '100';
    });

如果您只想更改变量的值,则无需再次声明。 所以你的代码看起来像:

var btn = document.getElementById('btn-here');
var val = document.getElementById('text-here').value;
btn.addEventListener("click", () => {
   val = '100';
});

下面的代码片段应该有助于阐明为什么问题中的代码没有达到预期的目标,并提供一个可行的替代方案。

代码片段

 var btn = document.getElementById('btn-here'); // in below, one is directly accessing the "value" var val = document.getElementById('text-here').value; btn.addEventListener("click", () => { // var val = '100'; // even if one removes "var", the value will still val = '100'; // not be assigned to element "text-here" console.log('val is now ', val); console.log('but, "text-here" element value remains: ', document.getElementById('text-here').value); }); // below is one way to achieve the expected objective // it uses no variables & directly manipulates the HTML elements document.getElementById("btn-here-works").addEventListener('click', () => { document.getElementById("text-here").value = '100'; }); // below is another alternative which uses variables // which resembles closely what the OP has described in their question // declare btn to hold the element with id "btn-here" const btn2 = document.getElementById('btn-here2'); // declare userInput to hold "text-here" (which is <input />) const userInput = document.getElementById('text-here2'); // add click event listner where userInput.value is assigned a value 100 btn2.addEventListener("click", () => { userInput.value = '100'; });
 <button id="btn-here">button</button> <input id="text-here" /> <button id="btn-here-works">button works</button> <br/><br/> <button id="btn-here2">button-2</button> <input id="text-here2" />

解释

  • 据我了解var val = document.getElementById('text-here').value; 提供对 HTML 元素的value属性的只读访问
  • 因此,当将100分配给val时,HTML 元素不受影响
  • 修改var val = '100'; to val = 100没有达到 OP 的预期
  • 相反,如果一个人通过使用诸如userInput类的变量来访问 HTML 元素(而不是它的value属性)
  • 然后,可以为userInput.value ,然后更改 HTML 元素的value属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM