【问题标题】:seting a cookie when closing bootstrap allert关闭引导警报时设置 cookie
【发布时间】:2022-01-03 10:16:02
【问题描述】:

当用户从引导程序关闭此警报时,我如何存储 cookie

<div class="alert alert-warning alert-dismissible fade show" role="alert">
  <strong>Holy guacamole!</strong> You should check in on some of those fields below.
  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>

我知道怎么用 "onclick" 来做,但是不修改上面的代码还有别的方法吗?

【问题讨论】:

    标签: javascript jquery twitter-bootstrap


    【解决方案1】:

    那么您是问如何在不修改元素的情况下将侦听器附加到 dom 元素?

    <script>
        $('.alert-dismissible button.btn-close').click(() => {
            // cookie stuff here.
        });
    </script>
    

    你可以定位他们,上面是使用jquery的。

    【讨论】:

    • 谢谢你的理解
    • 还有一个问题,你提到了 div,然后你提到了按钮。这是为了更好地定义你想听的按钮吗?
    • @MaxMuster 这是针对具有 btn-close 类的按钮,但前提是它是类 alert-dismissible 的相对对象。
    【解决方案2】:

    使用alert events 之一来触发您的代码

    Event Description
    close.bs.alert This event fires immediately when the close instance method is called.
    closed.bs.alert This event is fired when the alert has been closed (will wait for CSS transitions to complete).

    $(".alert").on("closed.bs.alert", (e) => {
      console.log("here's where I would set a cookie")
      
      // doesn't work in StackSnippet sandbox
      // document.cookie = "favorite_framework=Bootstrap; SameSite=None; Secure";
    })
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    
    <div class="container">
      <div class="alert alert-warning alert-dismissible fade show" role="alert">
        <strong>Holy guacamole!</strong> You should check in on some of those fields below.
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
    </div>

    【讨论】:

    • 谢谢,我还在消化,我需要更好地理解这个shothand ajax。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    • 1970-01-01
    • 2021-09-14
    • 2020-07-28
    • 1970-01-01
    • 2014-12-12
    相关资源
    最近更新 更多