Unobtrusive Javascript-Basic Implementation: How do I bind all elements of a particular class to a function in Javascript?

天大地大妈咪最大 提交于 2019-12-12 03:32:19

问题


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;
}

来源:https://stackoverflow.com/questions/36454598/unobtrusive-javascript-basic-implementation-how-do-i-bind-all-elements-of-a-par

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!