Bootstrap modal.show() 立即触发,而不是异步等待

问题描述 投票:0回答:1
modal-dialog bootstrap-modal bootstrap-5
1个回答
0
投票

您需要从

data-bs-*
中删除
button
属性,因为它们会自动触发模态,并且仅使用 JS 显示/隐藏模态:

  <button
      class="btn btn-primary w-100"
      onclick="Send();"
    >
      Invia
    </button>

JS模态实例:

    const modal = new bootstrap.Modal('#exampleModal');

演示:

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://getbootstrap.com/docs/5.3/assets/css/docs.css" rel="stylesheet">
  <title>Bootstrap Example</title>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>

<body class="p-3 m-0 border-0 bd-example m-0 border-0">

  <!-- Example Code -->


  <form abineguid="06622E9DA1A84EF183141C48C5CDF885">
    <div class="mb-3">
      <label for="recipient-name" class="col-form-label">Recipient:</label>
      <input type="text" class="form-control" id="recipient-name">
    </div>
    <div class="mb-3">
      <label for="message-text" class="col-form-label">Message:</label>
      <textarea class="form-control" id="message-text"></textarea>
    </div>

      <button
          class="btn btn-primary w-100"
          onclick="Send(event);"
        >
          Invia
        </button>
    
    
  </button>

  </form>



  <!-- Modal -->
  <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          ...
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>



  <script>
  
    const modal = new bootstrap.Modal('#exampleModal');



    function Send(e) {

e.preventDefault()

      var file_string = "https://jsonplaceholder.typicode.com/todos";
      console.log(file_string);


      fetch(file_string)
        .then((response) => response.json())
        .then((data) => {
          console.log("File uploaded successfully:", data);

          modal.show();

        })
        .catch((error) => {
          console.error("Error uploading file:", error);
        });
    }
  </script>
</body>

</html>

© www.soinside.com 2019 - 2024. All rights reserved.