简体   繁体   English

如何在 javascript 中传递变量

[英]How to pass a variable in javascript

I am building a bookmarlet based on this site: http://www.latentmotion.com/how-to-create-a-jquery-bookmarklet/我正在基于此站点构建一个bookmarlet:http://www.latentmotion.com/how-to-create-a-jquery-bookmarklet/

This is the code of bookmarlet:这是bookmarlet的代码:

javascript:(function(){
    var head=document.getElementsByTagName('head')0],
         script=document.createElement('script');
    script.type='text/javascript';
    script.src='http://myserver.com/bookmarlet-remote.js?' + Math.floor(Math.random()*99999);
    head.appendChild(script);
})(); 
void 0

How I can pass a variable from the bookmarlet (above code), to bookmarlet-remote.js?如何将 bookmarlet(上面的代码)中的变量传递给 bookmarlet-remote.js?

I've tried after var myNewvar='myValue', without success, Any Idea?我在 var myNewvar='myValue' 之后尝试过,但没有成功,有什么想法吗?

All JS code on a page (including bookmarklet code and scripts included have) have access to the global scope.页面上的所有 JS 代码(包括书签代码和包含的脚本)都可以访问全局 scope。 If you define a variable without the var prefix it will be available to all other scripts.如果您定义一个没有var前缀的变量,它将可用于所有其他脚本。

It might be a good idea to be explicit about this.明确这一点可能是个好主意。 do window.myVar = "foo";window.myVar = "foo"; to clearly signal that you are working with global variables.清楚地表明您正在使用全局变量。

Using var in the function makes it local to that function.在 function 中使用 var 使其成为 function 的本地变量。 To make it global you have to add it to the scope of the window , so:要使其全球化,您必须将其添加到 window 的window中,因此:

window.newVariable = window.newVariable || 'Your new value here';

OR或者

window['newVariable'] = 'Your new value here';

You'd create a public variable.您将创建一个公共变量。

window.rnd = Math.floor(Math.random()*99999);

In bookmarlet-remote.js you just access the variable.在 bookmarlet-remote.js 中,您只需访问该变量。

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

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