仅在第一次尝试时成功删除弹出窗口可见性

Popup visibility removal successful on first try only

以下代码的工作原理是它会导致警报出现并在 3 秒后消失。问题是,当我第二次触发它时(不刷新浏览器),它会出现但不会第二次超时并消失,除非单击 x。我怎样才能让它在没有用户退出的情况下不断出现和消失?

请看以下内容:

function appendWarning () {
    // missing
    if(!result) {
      $(".confirmAlert").append('class="alert alert-danger" role="alert">Oh snap! Something went terribly wrong!</div>');
    } else {
        var confPop = $(".confirmAlert").append('<div id="confrimedLuck" class="alert alert-warning alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' + rand + '</div>');
        console.log("confPop BANG!");
    }
    var cleanAlert = setTimeout(function(){ document.getElementById('confrimedLuck').style.display = 'none'}, 3000);
    console.log("cleanAlert executed!");
}

你的问题是你在追加,但是每次都将显示设置为 none 而不是删除它,所以你最终得到相同 id 的重复元素,并且只有 select第一个已经隐藏了。

不要将显示设置为 none,而是将其删除:

var cleanAlert = setTimeout(function(){ $('#confrimedLuck').remove() }, 3000);

或者,如果您愿意,您可以让它始终显示在 DOM 中,同时只需切换其显示 属性(使用 jQuery 最方便,因为您已经在使用它).

// missing
if(!result) {
  $(".confirmAlert").append('class="alert alert-danger" role="alert">Oh snap! Something went terribly wrong!</div>');
} else {
    var confPop = $("#confrimedLuck").show().parent();
    console.log("confPop BANG!");
}
var cleanAlert = setTimeout(function(){ $('#confrimedLuck').hide() }, 3000);
console.log("cleanAlert executed!");

问题是你只隐藏了在超时中第一次调用时创建的元素(通过将它的 display 属性 设置为 none),因为 getElementById 只访问第一个找到的具有指定 ID 的元素,这个第一个元素一次又一次地被隐藏,而其他新创建的 confirmedLuck div 保持不变和可见。

这应该有效:

function appendWarning () {
    // missing
    if(!result) {
      $(".confirmAlert").append('class="alert alert-danger" role="alert">Oh snap! Something went terribly wrong!</div>');
    } else {
        var confPop = $(".confirmAlert").append('<div id="confrimedLuck" class="alert alert-warning alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' + rand + '</div>');
        console.log("confPop BANG!");
    }
    var cleanAlert = setTimeout(function () {
        $('#confrimedLuck').remove(); // Completely remove the element (using jQuery) instead of just hiding it.
    }, 3000);
    console.log("cleanAlert executed!");
}