简体   繁体   English

如何使用按钮单击打开引导模态

[英]How to open bootstrap modal using a button click

I have developed a simple js pig game. 我已经开发了一个简单的js猪游戏。 You can see it here: http://creativeartbd.com/demo/game/js-pig-game 您可以在这里看到它: http : //creativeartbd.com/demo/game/js-pig-game

At first, it will open a Bootstrap Modal box to set a winning score. 首先,它将打开一个Bootstrap Modal框来设置一个获胜分数。 Now, the game will begin by click on the Roll Dice button. 现在,游戏将通过单击掷骰子按钮开始。

Well, now if you WIN then you can press the New Game button to re-play the game. 好吧,现在,如果您获胜,则可以按“新游戏”按钮来重新玩游戏。 Here, I want to open the bootstrap modal again when I click on the New Game button. 在这里,我想单击“新游戏”按钮时再次打开引导程序模版。 For that I have write this code: 为此,我编写了以下代码:

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

but it's showing me an error message on console log: 但它在控制台日志上显示了一条错误消息:

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

Maybe this is because of Javascript IIFE. 也许是因为Javascript IIFE。 I don't know exactly :( 我不知道:(

I have also tried with this code: 我也尝试使用此代码:

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

but no luck :( 但没有运气:(

My HTML and js code is a bit long that's why I don't put here. 我的HTML和JS代码有点长,这就是为什么我不放在这里。 You can find it here: https://jsfiddle.net/r8cga7L5/ 您可以在这里找到它: https : //jsfiddle.net/r8cga7L5/

Thanks. 谢谢。

Any specific reason you want the modal to open from JS? 您要从JS打开模式的任何特定原因吗?

Try this for the Bootstrap 4 approach: 对于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>

像这样修改按钮,效果很好

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

您可以这样称呼它:

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

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

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