[英]How can I make variables so that I don't have to repeat myself in future functions
WARNING!! 警告!! I AM A NOVICE THROUGH AND THROUGH
我是彻头彻尾的新手
Alright, so I know there have been a lot questions about Global variables, and I think that's what I'm looking for, but, not exactly. 好的,所以我知道有关全局变量的问题很多,我想这就是我想要的,但不完全是。 Lately I've been needing to call upon the same lines of code several times.
最近,我需要多次调用相同的代码行。
document.getElementById("example").style
or similar to little things like that but I need to continuously repeat. document.getElementById("example").style
或类似的小东西,但我需要不断重复。
My question is how do I make it so that I make one variable, outside of the function, to save time writing these lines? 我的问题是我该如何做,以便在函数之外创建一个变量,以节省编写这些行的时间?
What I've been seeing is to simply write it outside like this var inferno = document.getElementById("inferno");
我所看到的是像这样简单地将其写在外面
var inferno = document.getElementById("inferno");
but this is far from working. 但这远没有奏效。
This is my code right now, it's simple because I was just using it as a test, but can anyone help me? 这是我的代码,很简单,因为我只是将其用作测试,但是有人可以帮助我吗?
var inferno = document.getElementById("inferno");
function infernoClick () {
inferno.style.backgroundColor="red";
}
You have the right idea. 你有正确的主意。 Note, though, that the variable doesn't have to be global .
但是请注意,该变量不必是global 。 It just has to be where all of the code that wants to use it can use it.
它只是必须在所有要使用它的代码都可以使用它的地方。
For example, this creates a global: 例如,这将创建一个全局变量:
<script>
var inferno = document.getElementById("inferno");
function infernoClick () {
inferno.style.backgroundColor="red";
}
function somethingElse () {
inferno.style.color="green";
}
</script>
(Note that this needs to be after the markup creating the inferno
element.) (请注意,这需要在创建
inferno
元素的标记之后 。)
The problem with globals is that they can conflict with each other, and in fact the global "namespace" is really, really crowded already. 全局变量的问题在于它们可能彼此冲突,并且实际上全局“命名空间”已经非常拥挤。
You can avoid that by wrapping up the code that needs inferno
in a scoping function , like this: 您可以通过在作用域函数中包装需要
inferno
的代码来避免这种情况,如下所示:
<script>
(function() {
var inferno = document.getElementById("inferno");
function infernoClick () {
inferno.style.backgroundColor="red";
}
function somethingElse () {
inferno.style.color="green";
}
})();
</script>
That code creates an anonymous function and then calls it immediately, running the code inside. 该代码创建一个匿名函数,然后立即调用它,在内部运行代码。
Now inferno
is "global" to the functions that need it, but isn't actually a global. 现在
inferno
是“全球性”到需要它的功能,但实际上不是一个全球性的。
Let's take a further example: 让我们再举一个例子:
<script>
(function() {
var outer = 42;
function doSomethingCool() {
var inner = 67;
document.getElementById("someElement").onclick = function() {
alert("inner = " + inner + ", outer = " + outer);
};
}
// Can't use `inner` here, but can use `outer`
alert("outer = " + outer);
doSomethingCool();
})();
</script>
That code wraps everything in a scoping function, and the outer
variable is accessible everywhere within that scoping function. 该代码将所有内容包装在作用域函数中,并且
outer
变量在该作用域函数中的任何位置均可访问。 It also has a function, doSomethingCool
, which has a variable called inner
. 它还具有
doSomethingCool
函数,该函数具有一个称为inner
的变量。 inner
is only accessible within doSomethingCool
. inner
只能在doSomethingCool
访问。 Look at what doSomethingCool
does: It hooks up an event handler for when someElement
is clicked. 看一下
doSomethingCool
作用:当单击someElement
时,它会挂接事件处理程序。 It doesn't call the function, it just hooks it up. 它不调用函数,只是将其连接起来。
The really cool thing is that later , when someone clicks the element, that function has access to that inner
variable. 真正很酷的事情是, 稍后 ,当有人单击该元素时,该函数可以访问该
inner
变量。
And in fact, that's true for arguments you pass into the function as well. 实际上,对于传递给函数的参数也是如此。 One last example:
最后一个例子:
<input type="button" id="element1" value="One">
<input type="button" id="element2" value="Two">
<script>
(function() {
function hookItUp(id, msg) {
document.getElementById(id).onclick = function() {
alert(msg);
};
}
hookItUp("element1", "This message is for element1");
hookItUp("element2", "And this one is for element2");
})();
</script>
There, we have this function that accepts a couple of arguments, and we call it twice: Once to hook up click
on element1
, and again to hook up click
on element2
. 在那里,我们有这样的功能,接受一对夫妇的争论,我们把它叫做两次:一次是挂钩
click
上element1
,并重新挂钩click
上element2
。
The really cool thing here is that even though the clicks happen much later, after the calls to hookItUp
have long-since returned, the functions created when we called hookItUp
still have access to the arguments we passed to it — when we click element1
, we get "This message is for element1", and when we click element2
, we get "And this one is for element2." 这里真正很酷的事情是,即使单击发生的时间很晚,在很长一段时间以来都返回了对
hookItUp
的调用之后,当我们调用hookItUp
时创建的函数仍然可以访问传递给它的参数–单击element1
,得到“此消息是针对element1的”,并且当我们单击element2
,得到的是“这是针对element2的”。
These are called closures. 这些称为闭包。 You can read more about them on my blog: Closures are not complicated
您可以在我的博客上阅读有关它们的更多信息: 关闭并不复杂
That'll work, but only if the declaration appears after the point in the DOM where the element actually appears. 这将起作用,但是仅当声明出现在元素中实际出现的DOM点之后 。 Try moving your
<script>
to the very end of the <body>
. 尝试将
<script>
移到<body>
末尾。
Another thing you can do is use the window "load" event to make sure the whole DOM has been seen before your code runs. 您可以做的另一件事是使用窗口“ load”事件来确保在代码运行之前已经看到了整个DOM。
for example 例如
var myGlobalVars = {"inferno":null,"othervar":null}; // globals in their own scope
function clickMe(varName,color) { // generic function
myGlobalVars[varName].style.backgroundColor=color;
}
window.onload=function() {
// initialise after the objects are available
for (var o in myGlobalVars) myGlobalVars[o]=document.getElementById(o);
// execute
clickMe("inferno","red");
}
. 。 .
。
TJ Crowder gave a beautiful answer about scoping; TJ Crowder给出了关于范围界定的漂亮答案; just to add on that you can also use an immediately-invoked function expression to create a module with your UI elements, ie
补充说一下,您还可以使用立即调用的函数表达式来创建带有UI元素的模块,即
var UI = (function() {
...
return {
inferno: document.getElementById("inferno");
};
})();
...
UI.inferno.style = ...;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.