【问题标题】:Do function not have access to window object? [closed]函数不能访问窗口对象吗? [关闭]
【发布时间】:2020-05-02 20:19:23
【问题描述】:

为什么这段代码有效: '''<button type="button" id="clear" onclick="window.localStorage.clear();">delete accounts</button>''' 但这不会: '''

document.getElementsById('clear').addEventListener('click', function() {
  window.localStorage.clear()
});

'''

【问题讨论】:

  • 您是否收到特定的错误消息?你试过使用调试器吗?
  • 如何将脚本注入到 html 中?很可能脚本是在 html 之前加载的。

标签: javascript function object local-storage javascript-objects


【解决方案1】:

没有getElementsById 方法,因为 id 应该是唯一的。因此,您应该改用getElementById

document.getElementById('clear').addEventListener('click', function() {
      console.log(window)
      window.localStorage.clear()
});
<button type="button" id="clear">delete accounts</button>

【讨论】:

  • 谢谢。我不敢相信我错过了那个错字。 :)
  • 很高兴我能帮上忙。
猜你喜欢
  • 1970-01-01
  • 2017-06-07
  • 1970-01-01
  • 2011-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-26
  • 2018-06-09
相关资源
最近更新 更多