简体   繁体   English

我该如何进行变量设置,以免在以后的功能中重复自己

[英]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 . 在那里,我们有这样的功能,接受一对夫妇的争论,我们把它叫做两次:一次是挂钩clickelement1 ,并重新挂钩clickelement2

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.

相关问题 试图让我的函数能够拥有动态选择器,这样我就不必重复自己了 - Trying to make my functions be able to have dynamic selectors so i dont have to repeat myself 如何将后面代码中的循环创建的 Javascript 函数组合到一个函数中,这样我就不必重复了? - How could I combine Javascript functions created by a loop in the code behind in to one function so I don't have to repeat? 如何确保将计时器设置为每天4点半,所以我不必在Javascript中提及某个日期? - How can I make sure the timer is set to half 4 every day, so I don't have to mention a certain date in Javascript? 有什么办法可以做到这样我就不必重新声明 module.exports 的依赖项了吗? - Is there any way I can make it so I don't have to redeclare dependencies for module.exports? 我该怎么做才能使函数不堆叠? - What can I do so functions don't stack? 我该如何修改此代码,以便不必对对象进行排序? - How can I amend this code so that I don't have to sort an Object? 我怎样才能更改我的代码,以便我不必为所有单个记录使用脚本? - How can I change my code so that I don't have to use a script for all single record? 如何分隔嵌套函数,以免彼此干扰? - How can I separate my nested functions so they don't interfere with eachother? JavaScript - 如何使我可以重复 function? - JavaScript - How to make it so that I can repeat the function? 我想生成直到 3 的随机数,但我不想重复它们。 我怎样才能让它工作? - I want to generate random numbers till 3 but i don't want to repeat them. How can i make it work?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM