#

Javascript: Event an alle Children anhängen

 

 

Aufgabe:

wie kann man an alle Elemente eines bestimmten HTML-Tags ein Event anfügen.

 

Beschreibung:

HTML, Javascript

Das folgende Beispiel zeigt, wie alle P-Html Elemente in einem Div-Container Element mit einem click -Event Listener angefügt werden.

Dadurch reagieren künftig alle Html-Element mit dem Tagname:P auf den Maus-Klick

 

 

HTML Javascript Sample, code-snippet

<button type="button" title="optimize" onclick="set_Event_on_Children();">Test</button>

@*------------< script: Image-Tools >------------*@

<script>

    //----< events >----

    function set_Event_on_Children() {

        //----< set_Event_on_Children() >----

        //*sets an event to all children with match type

 

        var div = document.getElementById("ctlEditor_HTML");

        var elements = div.getElementsByTagName("p");

 

        //< loop: children >

        for (var i = 0; i < elements.length; i++) {

            //< attach event >

            elements[i].addEventListener("click", test);

            //</ attach event >

        }

        //</ loop: children >

        //----</ set_Event_on_Children() >----

    }

 

    function test() {

        //< Test >

        alert("Test");

        //</ Test >

    }

 

</script>

@*------------</ script: Image-Tools >------------*@

 

 

Javascript Code Optimierung

 

Die obere javascript Funktion kann dann verbessert werden durch die Verwendung von Parametern

 

<button type="button" title="optimize" onclick="add_Events_in_Editor();">Test</button>

@*------------< script: Image-Tools >------------*@

<script>

    //----< events >----

    function add_Events_in_Editor() {

        set_Event_on_Children("ctlEditor_HTML", "p", "click");

    }

   

 

    function set_Event_on_Children(sElementID,sChildren_Tagname,sEventname) {

        //----< set_Event_on_Children() >----

        //*sets an event to all children with match type

 

        var div = document.getElementById(sElementID);

        var elements = div.getElementsByTagName(sChildren_Tagname);

 

        //< loop: children >

        for (var i = 0; i < elements.length; i++) {

            //< attach event >

            elements[i].addEventListener(sEventname, test);

            //</ attach event >

        }

        //</ loop: children >

        //----</ set_Event_on_Children() >----

    }

 

    function test() {

        //< Test >

        alert("Test");

        //</ Test >

    }

 

</script>

@*------------</ script: Image-Tools >------------*@

 

 

 

Mobile

.

0123movie.net