How JavaScript Event Delegation Works

dynamicに作られてなくなるelementにはeventを付けづらい。 なので親にeventをつける方法でeventをdelegationする

// Get the element, add a click listener...
document.getElementById("parent-list").addEventListener("click", function(e) {
    // e.target is the clicked element!
    // If it was a list item
    if(e.target && e.target.nodeName == "LI") {
        // List item found!  Output the ID!
        console.log("List item ", e.target.id.replace("post-"), " was clicked!");
    }
});

もうちょっと複雑な例

parent DIVは複数のchildをもっていて そのなかで AtagのclassAのcss classを持つものを対象にする

// Get the parent DIV, add click listener...
document.getElementById("myDiv").addEventListener("click",function(e) {
    // e.target was the clicked element
    if(e.target && e.target.nodeName == "A") {
        // Get the CSS classes
        var classes = e.target.className.split(" ");
        // Search for the CSS class!
        if(classes) {
            // For every CSS class the element has...
            for(var x = 0; x < classes.length; x++) {
                // If it has the CSS class we want...
                if(classes[x] == "classA") {
                    // Bingo!
                    console.log("Anchor element clicked!");


                    // Now do something here....



                }
            }
        }

    }
});

references

results matching ""

    No results matching ""