如何在页面加载函数中设置的onclick函数中干净地使用JS变量 [英] how to cleanly use JS variables in an onclick function that are set in the page load function

查看:59
本文介绍了如何在页面加载函数中设置的onclick函数中干净地使用JS变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在

window.addEventListener('load', function() {
    var variable_name_1 = localStorage.getItem('var_1');
    ...
}

,我想移动该功能,使其仅在用户单击按钮时才能运行,在此处:

and I would like to move the functionality such that it only runs when the user clicks a button, in here:

function maketempuser() {
...
}

我可以在需要时调用该函数.但是该函数利用了load函数中的大量变量.有没有一种干净的方法来全球化"这些变量?还是我必须找到某种方法在html中添加所有这些变量:

I can get the function to call when I want. But the function utilizes tons of variables from the load function. Is there a clean way to "globalize" these variables? Or must I find some way to add all these variables in the html:

<button ... onclick='maketempuser(variable_name_1, variable_name_2, ...);' >

注意:javascript将运行相同的文件,我只是不希望每次用户重新加载页面时它都保持重新运行,因为发生了ajax mysql插入,因为此页面是一行允许用户注册的页面.

NOTE: the javascript will run the same file, I just don't want it to keep re-running every time the user reloads the page since there is an ajax mysql insert that occurs because this page is one in a line of pages that enables a user to register.

推荐答案

为了不污染很多变量(可以被其他应用覆盖)的全局范围,建议您创建一个具有应用特定名称的对象,也许像这样

To not pollute the global scope with a lot of variables (which can be overridden by other apps), I recommend you create an object with an app specific name, maybe something like this

var myAppVar = {};
window.addEventListener('load', function() {
  myAppVar.var_1 = localStorage.getItem('var_1');
  ...
}

这篇关于如何在页面加载函数中设置的onclick函数中干净地使用JS变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆