简体   繁体   English

在JavaScript小书签中定义多个全局函数

[英]Defining multiple global functions in a JavaScript bookmarklet

I'm working on a bookmarklet, which needs several functions. 我正在研究一个书签,需要几个功能。 Individually, I can define any function I need by calling something like: 单独地,我可以通过调用以下内容来定义所需的任何函数:

javascript:void(window.test1=function(){alert('hi');});

But as soon as I try to add a second function, it stops working. 但是,一旦我尝试添加第二个功能,它就会停止工作。

javascript:void(window.test1=function(){alert('hi');}window.test2=function(){alert('bye');});

Running this generates an error in the console saying "Unexpected identifier". 运行此命令将在控制台中生成一个错误,提示“意外标识符”。 I have tried separating the two function declarations with a semicolon, a space, and a carriage return (the latter two hex-encoded as %20 and %0A), inserting them between thus: 我尝试用分号,空格和回车符(后两个十六进制编码为%20和%0A)分隔两个函数声明,并在它们之间插入:

javascript:void(window.test1=function(){alert('hi');};window.test2=function(){alert('bye');});

This doesn't work either; 这也不起作用。 it yields the error message "Unexpected token". 它会产生错误消息“意外令牌”。

How do I define two functions consecutively in the context of a bookmarklet? 如何在小书签的上下文中连续定义两个函数?

Try wrapping all inner function in 1 function and define all needed function in inner function as properties/methods on window object as you are doing here. 尝试将所有内部函数包装在1个函数中,然后像在此处一样将内部函数中所有需要的函数定义为window对象上的属性/方法。

Thus: 从而:

javascript:void(function(){window.test1=function(){alert('hi');};window.test2=function(){alert('bye');}}());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM