【问题标题】:How do I steal the click event from an element?如何从元素中窃取点击事件?
【发布时间】:2015-06-10 18:04:45
【问题描述】:

长话短说:我试图让 Bootstrap 的模式窗口在页面加载时可见。

I copied a bit of HTML from W3Schools.

<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
        <p>Some text in the modal.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>

代码是关于如何制作一个模态窗口的,但不是在单击button 元素时触发它,而是希望它在页面加载时触发并完全摆脱按钮。当然,一种方法是隐藏按钮并搭载其点击事件,例如:

<button id="the-button" type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" style="display:none;">Open Modal</button>
<script type="text/javascript">
     $(function() { $('#the-button').click(); });
</script>

我宁愿从 HTML 中删除按钮,并在页面加载时发生与单击按钮时发生的相同的事情。

我在 Google Chrome 的检查器中查看了事件侦听器,但我不知道如何使用它来提取点击功能。它包含有关功能的信息,但不包含功能本身。

【问题讨论】:

  • 你不需要触发按钮点击。只需使用 $('#myModal').modal('toggle');在 document.ready 事件中
  • 或者您可以在按钮上使用display:none css,然后执行您之前建议的.click()

标签: javascript jquery html twitter-bootstrap bootstrap-modal


【解决方案1】:

这是一个可能的解决方案:https://jsfiddle.net/99x50s2s/60/

您不需要单独的按钮。如下图调用modal('show')函数即可,

var modalDialog = $('#myModal');
modalDialog.modal('show');

【讨论】:

    【解决方案2】:

    检查show attribute,默认情况下为真。

    所以你可以:

    <script>
    $(function() {
        $('#myModal').modal();
    });
    </script>
    

    【讨论】:

      【解决方案3】:

      在 jQuery 中还有一个事件load()。您不必窃取点击事件,只需在页面加载时触发您的函数:

      $( window ).load(function() {
          $( "#myModal" ).modal();
      });
      

      或者你甚至可以使用:

      $( document ).ready(function() {
          $( "#myModal" ).modal();
      });
      

      【讨论】:

        猜你喜欢
        • 2018-04-24
        • 1970-01-01
        • 2020-01-06
        • 2015-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多