将JS变量/变量值从第一个js文件中的函数传递到第二个文件

时间:2020-02-18 15:08:19

标签: javascript variables global-variables

是否可以仅使用原始JS在两个不同的JS文件之间传递变量而无需使用Node js?我只是在客户端执行此操作,没有使用服务器或其他任何工具。

在第一个文件(first.js)中,我有以下(缩短的)代码:

function appendImg(){
  var img = document.createElement('img');
  img.src = tempImg.src;
  document.body.appendChild(img);
  createImg(index++);

  img.onclick = function(event){
    window.location.href = "second.html";
    }
}

“ img”来自我在文件开头编写的给定图像数组中的一系列操作,src分配等。

我想做的是,当我单击某个图像时,它会将我重定向到另一个HTML页面,如您所见,在该页面上我想显示与单击相同的图像。

我遇到了麻烦,因为我的img变量在函数中声明,而第二个JS文件无法识别它。

我该如何更改?

2 个答案:

答案 0 :(得分:1)

正如@Keith所说,您正在重新加载页面,因此您将丢失所有内存。即使将其放在全局范围内,另一个函数也可以读取它,它还是消失了。

您可以使用的一种方法是在url参数中添加一些参考:

function appendImg(){
  var img
  img = document.createElement('img');
  img.src = tempImg.src;
  document.body.appendChild(img);
  createImg(index++);

  img.onclick = function(event){
    window.location.href = "second.html?img_src=" + tempImg.src;
    }
}

然后在第二页中编写代码以检查位置的url参数。

答案 1 :(得分:1)

最快的方法是将图像作为查询字符串值传递。例如:

 // Make the image name safe to include in a URL
 const imageUrl = encodeURIComponent(img.src);

 // Pass the image as a query string value
 window.location.href = `second.html?image=${imageUrl}`;

second.html上的JavaScript中,您需要解析查询字符串以获取图像路径。参见:How can I get query string values in JavaScript?