【问题标题】:Why can't I set the "value" property of my HTML element? [closed]为什么我不能设置我的 HTML 元素的“值”属性? [关闭]
【发布时间】:2018-07-14 23:37:56
【问题描述】:

当我尝试运行以下代码时,我不断收到错误消息:

无法在“id”处设置 null 的属性“值”

我尝试将属性从value 更改为innerHTML,但没有成功。如果您能帮助我,我将不胜感激。谢谢!

<div class="input-field s6 col" style="color: white; background-color:transparent;">
  <input id="avatar_url" id="ipoza" type="text" onfocus="style='background-color:white;'" onblur="style='background-color:transparent'" value="http://i01.c.aliimg.com/img/ibank/2014/101/288/1614882101_2028072840.jpg"> <label for="avatar_url"><p>Poza de Profil</p></label>
</div>

<button onclick="i()"></button>
<script type="text/javascript">
  function i() {
    document.getElementById("ipoza").value = "Link";
  }
</script>

【问题讨论】:

  • &lt;input id="avatar_url" id="ipoza" ... - 元素只能有一个id
  • 不允许使用多个 id,但您可以使用 class="avatar_url" 代替。类可以添加到多个元素中,这样会更有用。
  • 尝试通过 HTML 验证器运行您的 HTML,例如 validator.w3.org,它将提供有用的 Line 2, Column 29: duplicate specification of attribute "ID" &lt;input id="avatar_url" id="ipoza" type="text" onfocus="style='background-colo…
  • 另外,onfocus="style='background-color:white;'" onblur="style='background-color:transparent'" 这样的代码很难阅读和调试。相反,只需编写一个简单的 CSS 规则 #iposa:focus { background-color: white; }

标签: javascript html selector


【解决方案1】:

每个元素只能有一个id。您的input 有 2 个ids,这是不允许的。只需给它一个idipoza,这样您就可以使用document.getElementById("ipoza") 选择它。

<div class="input-field s6 col" style="color: white; background-color:transparent;">
  <input id="ipoza" type="text" onfocus="style='background-color:white;'" onblur="style='background-color:transparent'" value="http://i01.c.aliimg.com/img/ibank/2014/101/288/1614882101_2028072840.jpg"> <label for="ipoza"><p>Poza de Profil</p></label>
</div>

<button onclick="i()"></button>
<script type="text/javascript">
  function i() {
    document.getElementById("ipoza").value = "Link";
  }
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 2011-10-13
    • 2021-11-28
    • 2021-04-11
    • 1970-01-01
    • 2014-09-22
    • 2012-01-06
    相关资源
    最近更新 更多