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

时间:2015-04-30 20:24:48

标签: javascript scope settimeout

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

请参阅以下内容:

([1-9]\d{3,}|9[6-9]\d|95[5-9])

2 个答案:

答案 0 :(得分:2)

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

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

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!");

答案 1 :(得分:1)

问题是你只是在超时中隐藏了第一次调用时创建的元素(通过将其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!");
}