我对 JS 和小书签有点陌生。
我正在修改一些现有代码;其写法如下(出于教育目的,我过度简化了实际代码):
javascript: 1 && function(e) {
var t = "";
t += "<style>",
t += ".somestyle-header{ background-color: #0171C5 !important }",
t += "</style>",
t += '<div class="somestyle-header">Test</div>',
t += "";
e("body").append("<div id='something'> </div>"), e("#something").append(t)
}($myvariable);
现在,这当前有效,它创建一个名为“something”的DIV,然后将所有内容附加到变量“t”上 到它。换句话说,它将变量 "t" 上的任何内容添加到当前站点的 HTML 中(假设该站点设置了 $myvariable某处)。
我正在尝试做类似的事情,但我有以下问题:
- 如何在函数开头删除 1 并使其正常工作?
- 如何才能使其在每个页面上都正常工作? $myvariable 最后是否存在。
另外,如果有人可以解释一下最开始的 1 和最后的 $myvariable 正在做什么,以及为什么如果我删除这些部分中的任何一个,这段代码就不起作用?
我希望我能做这样的事情:
javascript: (function() {
if (!($ = window.jQuery)) {
script = document.createElement( 'script' );
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
script.onload=launchTheSplash;
document.body.appendChild(script);
}
else {
launchTheSplash(e);
}
function launchTheSplash(e) {
var t = "";
t += "<style>",
t += ".somestyle-header{ background-color: #0171C5 !important }",
t += "</style>",
t += '<div class="somestyle-header">Test</div>',
t += "";
e("body").append("<div id='something'> </div>"), e("#something").append(t)
}
}());
这样:
- 我检查 JQuery 是否存在
- 无论 $myvariable 是否存在,我都会启动我的小书签
但是如果我删除开头的 1 或结尾的 $myvariable ,我的代码似乎根本不起作用。如果我这样做,我会得到一个 Uncaught TypeError: e is not a function
希望这足够清楚。提前致谢!
编辑:
我尝试了以下建议:
javascript: (function() {
if (!($ = window.jQuery)) {
script = document.createElement( 'script' );
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
script.onload=launchTheSplash();
document.body.appendChild(script);
}
else {
launchTheSplash();
}
function launchTheSplash(e = $) {
var t = "";
t += "<style>",
t += ".somestyle-header{ background-color: #011515 !important }",
t += "</style>",
t += '<div class="somestyle-header">Test</div>',
t += "";
e("body").append("<div id='something'> </div>"), e("#something").append(t);
}
}());
但是在某些页面上似乎不起作用;例如 - 如果我尝试在 www.apple.com 网站上运行书签,它会返回 Uncaught TypeError: e is not a function
任何想法表示赞赏!再次感谢!
最佳答案
为了立即执行函数,可以使用 IIFE( https://developer.mozilla.org/en-US/docs/Glossary/IIFE )。立即执行函数的正确语法是 -
(function(text){
console.log(text);
})('Hello World')
在您的情况下 e
应该是 jquery 元素,因此每当您调用启动函数时,您都应该在其中传递 $
。
看看这个片段 - https://jsitor.com/E8JW18YD-
关于javascript - 未捕获的类型错误 : e is not a function on a JS function for a bookmarklet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54116212/