简体   繁体   中英

Is it a bad programming practice setting DOM elements as global variables in JavaScript/jQuery?

For example, I have this HTML :

<script src="test.js"></script>
<script>
$(document).ready(function() {
    initFields();
});
</script>

<input id="input" type="text">

And my JS :

var $input;

function initFields() {
    $input = document.getElementById("input"); //or $('#input) in jQuery
}

This way, I can access $input.value at any time (for example when submitting a form, or cleaning the field, etc), so that the variable becomes reusable. My doubt is: is it considered a bad practice to set DOM elements as global variables?

Sometimes global variables are unavoidable, but they're always regrettable. I would recommend creating one global object, and filling it up with references to DOM elements you want to refer to.

Eg, in the global scope:

var $elements = {
    $input  : $('#input'),
    $header : $('#header'),
    // etc, etc
};

Bear in mind that all global variables are just properties of the window object. One of the bigger issues in creating global variables in javascript is that you might accidentally overwrite a property on window , which can have serious consequences that are difficult to debug. If you're only defining one global variable (as in this example), you probably won't run into trouble, but if you're defining dozens of variables for different DOM elements or whatever, your program may quickly become hard to maintain, and hard to debug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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