【问题标题】:This code for a chrome extension is not working, and I have no Idea这个 chrome 扩展的代码不起作用,我不知道
【发布时间】:2017-06-02 07:46:15
【问题描述】:

我正在为 Roblox 网页开发这个小型 chrome 扩展程序,但由于某种原因,它根本不想正常工作。

错误是

Uncaught TypeError: Cannot set property 'background' of undefined
at extension_update (themeManager.js:7)
at themeManager.js:14

这是代码:

var colorOnePath = document.getElementsByClassName("navbar-fixed-top rbx-header");
var colorTwoPath = [document.getElementsByTagName("body"), document.getElementsByClassName("content")];    

var color = ["#008919", "#000000"];

function extension_update() {
    colorOnePath.style.background = color[0];
    colorTwoPath[0].style.background = color[1];
    colorTwoPath[1].style.background = color[1];

    setTimeout(1000, extension_update)
};

extension_update()

我不知道为什么代码是这样设置的,但是无论如何,有什么地方有问题吗?我找不到修复的地方。谢谢!

【问题讨论】:

  • 注意 - document.getElementsByTagName("body")[0] === document.body

标签: javascript google-chrome google-chrome-extension roblox


【解决方案1】:

getElementsByClassName 将始终返回一个类似数组的元素集合——即使只有一个。因此,在您的代码中,您不是在集合中的第一个元素上设置 style.background 属性,而是尝试在 collect 本身上设置它 - 因为该集合没有 style 属性,你得到你所看到的错误。尝试将您的代码更改为:

var colorOnePath = document.getElementsByClassName("navbar-fixed-top rbx-header")[0];
var colorTwoPath = [document.getElementsByTagName("body")[0], document.getElementsByClassName("content")[0]];    

var color = ["#008919", "#000000"];

function extension_update() {
    colorOnePath.style.background = color[0];
    colorTwoPath[0].style.background = color[1];
    colorTwoPath[1].style.background = color[1];

    setTimeout(1000, extension_update);
}

extension_update();

(我还冒昧地在缺少分号的地方添加分号,并在不必要的地方删除它们)。

【讨论】:

  • colorOnePath.style.background[0] ?你的意思是colorOnePath[0].style.background :p - 我个人会将[0] 添加到getElementsBy* 的所有结果中
  • @JaromandaX -- 很好的收获和很好的推荐 -- 相应更新 -- 谢谢!
  • 另一个document.getElementsByTagName("body")[0] === document.body :p
  • colorTwoPath 仍然必须是colorTwoPath[0]colorTwoPath[1]
  • 哦,你会认为这不是我的日常工作:p 已修复(再次)——谢谢!
猜你喜欢
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
  • 2020-01-11
  • 1970-01-01
  • 2015-08-05
  • 1970-01-01
  • 2020-09-19
  • 2014-01-17
相关资源
最近更新 更多