如何通过点击按钮来打开引导模态

时间:2019-03-26 05:54:41

标签: javascript html

我开发了一个简单的js猪游戏。您可以在这里看到它:http://creativeartbd.com/demo/game/js-pig-game

首先,它将打开一个Bootstrap Modal框来设置一个获胜分数。现在,游戏将通过单击掷骰子按钮开始。

好吧,现在,如果您获胜,则可以按“新游戏”按钮来重新玩游戏。在这里,我想单击“新游戏”按钮时再次打开引导程序模版。为此,我编写了以下代码:

document.querySelector(".btn-new-game").addEventListener("click", function () {
    init();     
    document.getElementById("myModal").modal('show');       
});

但是它在控制台日志上显示了一条错误消息:

Uncaught TypeError: document.getElementById(...).modal is not a function

这也许是因为Javascript IIFE。我不知道:(

我也尝试过使用此代码:

document.getElementById("myModal").click();     

但没有运气:(

我的HTML和js代码有点长,这就是为什么我不在这里。您可以在这里找到它:https://jsfiddle.net/r8cga7L5/

谢谢。

3 个答案:

答案 0 :(得分:0)

您要从JS打开模式的任何特定原因吗?

尝试使用Bootstrap 4方法:

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

答案 1 :(得分:0)

像这样修改按钮, 运行正常

<button data-toggle="modal" data-target="#myModal" class="btn btn-new-game">New Game(+)</button>

答案 2 :(得分:-1)

您可以这样称呼它:

document.getElementById("myModal").modal();