Unobtrusive Javascript-Basic Implementation: How d

2019-09-03 20:24发布

问题:

So I was reading this SO question earlier, and I am currently trying to get a basic implementation of Unobtrusive javascript working, but I don't know where I'm struggling. Normally this is something I would struggle with for much longer until I figure it out on my own, but I'm starting to get in a bit of a time crunch...

I have a several elements within my HTML document with a class called "RMButton", and I'm trying to make all of my elements with this class call a function called "RemoveQBox" (For clarity. The QBox is a DIV element, and the objects of class "RMButton" are small buttons that remove the div from the document). RemoveQBox, is already written and works just fine when I use inline JS to call it (Ex: REMOVE), but for some reason my binding within JS isn't really working out. Anybody know what I'm missing here?

Top of my Javascript file

var DBSetFields = [];
var NumQBoxes = 1;

window.onload = function() {
    RMNodeList = document.getElementsByClassName("RMButton");
    for (var i = 0; i < RMNodeList.length; ++i) {
        console.log(RMNodeList[i]);
        RMNodeList[i].onclick = RemoveQBox;

    }
};

TLDR: How do I bind all elements of a particular class to a function in Javascript?

edit:

    function RemoveQBox(e){
    console.log("Remove");
    var RemoveButton = this; //this == e.currentTarget
    console.log(RemoveButton);
    var QBox = RemoveButton.parentNode;
    QBox.remove();
    NumQBoxes -= 1;
}