【问题标题】:Can't change attribute of input tag using Javascript无法使用 Javascript 更改输入标签的属性
【发布时间】:2017-07-05 05:40:27
【问题描述】:

我有一个<input> 标记,我想以编程方式对其进行更改。输入没有内部文本,它将其值保存在 aria 属性中。

所以,这里是<input>

<input type="text" id="foo" aria-valuemin="1" aria-valuemax="10" autocomplete="off" role="spinbutton" aria-valuenow="1">

考虑我们将标签保存到以下bla变量中:

var bla = document.getElementById("foo");

下面是我尝试使用的命令列表。但它们都不起作用。

  • bla.value = 2;
  • bla.value = "2";
  • bla.setAttribute("aria-valuenow",2);
  • bla.setAttribute("aria-valuenow","2");

任何想法为什么?元素的id 是唯一的,我检查了它。 我正在研究别人的代码。有没有可能其他开发者改变了&lt;input&gt;的行为?

【问题讨论】:

  • input.value = "2"; 应该可以工作。您是否有可能有另一个 ID 为 input 的元素?
  • @FTM 将 id 更改为独特的东西
  • 我放在这里的 id 只是一个例子。真实身份完全不同,而且肯定是独一无二的。
  • @FTM 我认为您应该发布更多数据 - 更多 HTML,更多 Javascript - 有什么不对劲,不清楚是什么。
  • 在执行此代码之前必须有一些代码中断,否则bla.value = "2";bla.setAttribute("aria-valuenow","2"); 应该可以正常工作。您可以在浏览器上调试并检查是否有问题。

标签: javascript input


【解决方案1】:

正如我的其他用户所指出的,请在命名元素的 id 时使用唯一 ID。以下是使用setAttribue() 解决您的问题的方法。

var input = document.getElementById("input");
input.setAttribute("aria-valuenow",2); // To set attribute to input element
console.log(input.hasAttribute('aria-valuenow')) // To check if input has the mentioned attribute
console.log(input.getAttribute('aria-valuenow')); // To access the value of the attribute
&lt;input type="text" id="input" aria-valuemin="1" aria-valuemax="10" autocomplete="off" role="spinbutton" aria-valuenow="2"&gt;

【讨论】:

  • id 不是问题。 id 是唯一的。在我的情况下,setAttribute 函数不起作用。这就是我发布这个问题的原因。
  • console.log() setAttribute() 之前和之后的元素。检查结果。
  • 已检查,没有变化。
  • 你能和我分享一下结果吗?
  • 初始值为1。运行您推荐的命令后,hasAttribute 的结果为truegetAttribute 的结果为1。因此,它并没有像我想使用 setAttribute 方法那样更改为 2。
【解决方案2】:

你可以使用,

document.getElementById("mytext").value = "My value";

【讨论】:

  • 这个答案与PO的问题无关。您刚刚从 SO 中的另一个答案中复制了它。
  • 正如我在问题中所写的那样,我试过了,但没有用。
猜你喜欢
  • 2011-01-30
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2012-11-27
  • 1970-01-01
  • 2019-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多