从 class 中删除按钮 onclick

Deleting a button onclick from a class

onclickclassobliterate 的按钮,我想让我的以下代码获取一堆相同的按钮,除了它的唯一 ID,然后将其删除。 Buttons 可以通过 innerHTML 随时从用户输入。我想在 confirm 之后删除按钮 onclick 这是我当前的代码:

document.getElementsByClassName('obliterate').onclick = function() {
      if (confirm('Are you sure you want to delete this?')){
         //get this then remove it with remove(this.id);
    }
}

您可以使用 bind 函数提供上下文,因此在您的情况下:

element.onclick = function(){ ... }.bind(this);

应该直截了当,将事件处理程序附加到元素,删除元素

var elems = document.querySelectorAll('.obliterate');

for (var i=0; i<elems.length; i++) {
    elems[i].addEventListener('click', function() {
        if ( confirm('Are you sure you want to delete this?') ) {
            this.parentNode.removeChild(this);
        }
    }, false);
}

如果页面加载时元素不存在,则必须委托,没有库的情况下这样做可能会有些复杂,具体取决于您要匹配的选择器、点击元素内是否有子元素等,但是这是一个简化版本

document.addEventListener('click', function(event) {
    var clicked = event.target;
    var elems   = [].slice.call(document.querySelectorAll('.obliterate'));

    if ( elems.indexOf(clicked) !== -1 ) {
        if ( confirm('Are you sure you want to delete this?') ) {
            clicked.parentNode.removeChild(clicked);
        }
    }
}, false);

FIDDLE