Frage

I have this function:

function createElement() {
    var element1 = document.createElement("div");
    element1.id = "el1";
    //...
}

the problem is that when I create another function, let say editElement(), I cannot access element1 from within the new function as it's out of scope.

I could declare element1 outside of those functions, but then the problem is that element1 gets declared all the time. But I may need to create the element only in the fraction of the cases, only when a user presses a button and creadeElement() gets called. I want to save system resources and call document.createElement("div") only when I really need it, but I also need to access it from within multiple functions. Is there a way to do it?

War es hilfreich?

Lösung

you can simply assign your new element to window so it available in global scope

function createElement() {
    window.element1 = document.createElement("div"); //Meke new element global.
    element1.id = "el1";
}

function useElement() {
    //now you can use element1 directly. as it is inside the global scope.
}

Andere Tipps

Instead, do something like this:

var element1 = null;
function createElement() {
    element1 = document.createElement("div");
    element1.id = "el1";
    //...
}

function useElement() {
    if(!element1)createElement()
    //...
}

This will make the element available outside the createElement function, but won't create the element until it's needed.

You can use an object:

var elementHandler = {
    createElement: function() {
        this.element1 = document.createElement("div");
        this.element1.id = "el1";
        // ...
    },
    editElement: function() {
        // Use this.element1 here...
    }
};

You call createElement and editElement like this:

elementHandler.createElement();
elementHandler.editElement();

(Or you might just call them create and edit as there's no need to repeat the word "element" all over the place...)

If hooking them up to an event, be sure you call them such that elementHandler is this within the call:

// Using an anonymous function
someElement.addEventListener("click", function() {
    elementHandler.createElement();
}, false);

// Or using ES5's `bind`
someElement.addEventListener("click", elementHandler.createElement.bind(elementHandler), false);

// *NOT* like this:
someElement.addEventListener("click", elementHandler.createElement, false);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top