删除计时器上动态添加的div

时间:2018-08-12 11:23:32

标签: javascript jquery

我希望div出现一小段时间然后消失。

因此,我只需单击一个按钮即可动态创建div,然后在完成一些工作后,希望将其从DOM中删除。

所以,我像这样设置了一个计时器:

var contentJoinTab = $("#...");
var divIdSubscribePleaseWait = "div-subscribe-pleasewait";


btnSubscribe.on("click", function (event) {

    displaySubscriptionWait();

    postMailingListSubscription();

});

function displaySubscriptionWait() {
    var s = `<div id = ${divIdSubscribePleaseWait} class = "${classMailingListPleaseWait}">Please wait...</div>`;

    contentJoinTab.append(s);
};

function postMailingListSubscription() {

    // fake for now
    window.setTimeout(function() {
        removeSubscriptionWait();
    }, 4000);

};

function removeSubscriptionWait() {
    contentJoinTab.parent(`${divIdSubscribePleaseWait}`).remove();

   // I've even tried the following to no avail
   // $(`${divIdSubscribePleaseWait}`).remove();
   // contentJoinTab.find(`${divIdSubscribePleaseWait}`).remove();
};

但是,即使对remove()方法的调用没有错误,我尝试删除的div仍保留在DOM中并且可见。

我确实了解事件传播,但我的理解是与此处无关。如果我想将事件附加到动态创建的click或其任何父对象的div(或任何其他事件)上,那将是有意义的。

4 个答案:

答案 0 :(得分:2)

呼叫#时您可能会错过removeSubscriptionWait,并且""也需要id = ${divIdSubscribePleaseWait}。 如果不清楚,请查看以下更改:

function displaySubscriptionWait() {
    var s = `<div id = "${divIdSubscribePleaseWait}" class = "${classMailingListPleaseWait}">Please wait...</div>`;

    contentJoinTab.append(s);
};

function postMailingListSubscription() {

    // fake for now
    window.setTimeout(function() {
        removeSubscriptionWait();
    }, 4000);

};

function removeSubscriptionWait() {
    contentJoinTab.parent(`#${divIdSubscribePleaseWait}`).remove();

   // I've even tried the following to no avail
   $(`#${divIdSubscribePleaseWait}`).remove();
};

答案 1 :(得分:0)

您可以通过将div的externalHTML设置为null来实现

function addDiv() {
  let s = "<div id='tempDiv'>Temporary Div</div>"
  let root = document.getElementById("root")
  root.innerHTML += s;
}

function removeDiv() {
  let theDiv = document.getElementById("tempDiv");
  theDiv.outerHTML=""
}


addDiv()

setTimeout(removeDiv,2000)
<div id=root>

</div>

答案 2 :(得分:0)

您已将该div作为contentJoinTab的子项追加,但是当您将其删除时,您正在寻找它作为contentJoinTab的父项

您还需要在选择器中添加ID前缀

尝试更改

contentJoinTab.parent(`${divIdSubscribePleaseWait}`).remove();

收件人

contentJoinTab.find(`#${divIdSubscribePleaseWait}`).remove();

答案 3 :(得分:0)

更新 removeSubscriptionWait 功能:

function removeSubscriptionWait() {

    contentJoinTab.find('#'+`${divIdSubscribePleaseWait}`).remove();
};