【问题标题】:DOM: Delete newly created 'article' element with newly created delete button within onclick event?DOM:在 onclick 事件中使用新创建的删除按钮删除新创建的“文章”元素?
【发布时间】:2016-04-17 14:14:13
【问题描述】:

我有一个 section 元素,其中包含一个 article 元素。另外,我有一个带有 'onclick' 事件的输入按钮。每当触发此事件时,都会有一个新的文章元素附加到具有 unique id 的 section 元素。 newArticle 元素包含一个标签、文本框和一个删除按钮。所有这三个元素都是在点击事件中创建的。

document.getElementById("addRow").onclick = function () {

    var newCustomerlbl = document.createElement("label");
    newCustomerlbl.innerHTML = "Cutomer Name: ";
    var newCustomertxt = document.createElement("input");
    newCustomertxt.setAttribute("type", "text");

    var delBtn = document.createElement("input");
    delBtn.setAttribute("type", "button");
    delBtn.setAttribute("value", "Delete");
    delBtn.setAttribute("id", "btnDelete");

    var newArticle = document.createElement("article");
    newArticle.appendChild(newCustomerlbl);
    newArticle.appendChild(newCustomertxt);
    newArticle.appendChild(delBtn);

    var customerSection = document.getElementById("customerRecords");

    var customerArticles = customerSection.getElementsByTagName("article");

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

        var lastDigit = i + 1;

        var newArticleValue = "article" + lastDigit;
        newArticle.setAttribute("id", newArticleValue);
    }

    customerSection.appendChild(newArticle);
}

现在我想要的是每当用户单击新创建的附加删除按钮时,只有该特定文章被删除而不影响其余文章。

这是my jsFiddle 代码。

【问题讨论】:

    标签: javascript html dom button sections


    【解决方案1】:

    如果你不想使用 jQuery,你可以在你的按钮上添加事件监听器:

    delBtn.addEventListener('click', function () {
        this.parentElement.remove();
    }, false);
    

    https://jsfiddle.net/3nq1v5e1/

    【讨论】:

    • 它工作得非常好。如果可以的话,投票给我的Q。我已经改变了格式。
    【解决方案2】:

    您需要在新创建的删除按钮上绑定一个事件监听器。您关于使用 $(this) 的示例代码表明您正在使用 JQuery,但在其余代码中您没有使用任何 JQuery?

    如果您使用的是 JQuery,事情变得非常简单,只需添加类似的内容

    $(document).on('click','.btnDelete', function(){
       $(this).closest('article').remove();
    });
    

    (记得给删除按钮一个 CLASS 而不是 ID,因为会有多个删除按钮)。

    如果您不使用 JQuery,则需要在每次创建新的删除按钮时添加事件侦听器

    newArticle.appendChild(delBtn);
    delBtn.onclick = function(.....
    

    等等

    【讨论】:

    • 事件监听器功能给了我想要的结果,但 J-Query 不工作。甚至 J-Query 也阻止了添加新文章的逻辑。你能告诉我为什么会这样吗?
    • 你是否像w3schools.com/jquery/jquery_get_started.asp那样在页面中添加了JQuery
    猜你喜欢
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 2015-07-05
    • 2014-01-24
    • 2018-10-30
    相关资源
    最近更新 更多