简体   繁体   English

如何在没有消息时隐藏Bootstrap警报框

[英]How to hide Bootstrap alert box when no message

I made a simple alert box with Bootstrap like this 我用这样的Bootstrap制作了一个简单的警报框

<div class="alertBox">
     <span role="alert" class="alert alert-info"> bag.session.username </span>
</div>

When there is no alert (box is empty), the box still shows on the page like this. 当没有警报(框为空)时,该框仍然显示在页面上。 在此输入图像描述

So I tried to hide it when it's empty with like so: 所以我试图隐藏它,当它是空的像这样:

<script type="text/javascript">
$(document).ready(function () {
    if (bag.session.username) {
        $(".alertBox").show();
    }
    else {
        $(".alertBox").hide();
    }
});
</script>

This basically says if an alert message is there, show the box, if not, hide it. 这基本上表示如果有警告消息,则显示该框,如果没有,则隐藏它。 However, this does not work as expected. 但是,这不能按预期工作。 The box is there until there is no alert. 盒子在那里直到没有警报。 How can I solve this? 我怎么解决这个问题?

Make sure to initially hide your alert box. 确保最初隐藏您的警报框。 Also it looks like your putting a JavaScript variable right into your HTML. 此外,您似乎将JavaScript变量放入HTML中。 Also the string bag.session.username may always evaluate to true. 字符串bag.session.username也可能总是评估为true。 Maybe this? 也许这个?

<script type="text/javascript">
$(document).ready(function () {
    if (typeof bag.session.username != "undefined") {
        $(".alertBox span").text(bag.session.username);
        $(".alertBox").show();
    }
    else {
        $(".alertBox").hide();
    }
});
</script>

The below code should help you solve your problem. 以下代码可以帮助您解决问题。 Let me know if you have any questions 如果您有任何疑问,请告诉我

<style>
        .foo{
            display: none;
        }
</style>

HTML and JS will be HTML和JS将是

<body>
    <div class="alertBox">
        <span role="alert" class="alert alert-info"></span>
    </div>
    <script type="text/javascript">
        $(document).ready(function () {
            $("span.alert").each(function(){
                if(!$(this).text().trim().length){
                    $(".alertBox").addClass("foo");
                }
            })

        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM