我的用户脚本没有'我不工作;我不知道为什么(过度使用var关键字)
My userscript doesn't work and I don't know why (overuse of var keyword)
嘿,伙计们,我刚刚发现了用户脚本的愚蠢之处,我想创建一个。从有限的在线教程中,我设法想出了这个。
// ==UserScript==
// @name My add on
// @description A script that adds a green div to the bottom of the page
// @include http://*
// @grant none
// ==/UserScript==
function createDiv(){
var userBar=document.createElement('DIV');
var userBar.style.height='80px';
var userBar.style.width='100%';
var userBar.style.backgroundColor='green';
document.body.appendChild(userBar);
}
createDiv();
这只是一个测试脚本,它在页面底部添加了一个绿色div。不幸的是,它在实现时什么都不做。
这个问题是因为您总是在前面写var。您只能在声明期间执行此操作。
这是正确的:
function createDiv(){
var userBar=document.createElement('DIV');
userBar.style.height='80px';
userBar.style.width='100%';
userBar.style.backgroundColor='green';
document.body.appendChild(userBar);
}
createDiv();
此外,由于您说过要将其添加到网站底部,您可以在将元素添加到正文之前添加:
userBar.style.position='absolute';
userBar.style.bottom='50px';
试试这个:
...
var body = document.getElementsByTagName("body")[0];
body.appendChild(userBar);
相关文章:
- 为什么delete关键字的作用与预期相反
- 为什么$scope和'这'关键字在控制器内部可互换使用
- 为什么在构造函数函数中使用此关键字
- 为什么import关键字有用
- 为什么在JSON中需要exclusiveMinimum和exclusiveMaximum关键字
- 为什么在没有 var 关键字的情况下分配给变量时会出现引用错误
- JavaScript:古代代码使用“new”关键字启动简单对象.为什么
- 为什么 JavaScript 函数需要有关键字“async”?“等待”关键字还不够吗?
- 为什么无法使用 const 关键字分配 JavaScript 对象的常量属性
- RegExp / Jquery / Isotope 按关键字搜索和过滤:不使用某些关键字组合,为什么
- Javascript:为什么有些变量在( )中,有些变量在关键字之前
- 为什么这个关键字不是指独立JS函数中的窗口
- 为什么数学对象在javascript中不需要新关键字
- 我没有'我不明白为什么;这个“;关键字dons'I don’我没有预料到的那么管用
- 为什么我们需要“;新的“;关键字
- 我的用户脚本没有'我不工作;我不知道为什么(过度使用var关键字)
- 为什么实例没有't在没有prototype关键字的情况下继承添加到构造函数的属性
- 为什么不是在 JavaScript 中匿名函数之外访问“this”对象的关键字
- 为什么函数在构造函数中声明时不使用new关键字
- 为什么关键字“this”在HTML和JS中不起作用