如何窃取元素的点击事件?

How do I steal the click event from an element?

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

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>

代码是关于如何制作模态 window 的,但我希望它在页面加载时触发,而不是在单击 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 的检查器中的事件侦听器,但我不知道如何使用它来提取点击功能。它包含有关功能的信息,但不包含功能本身。

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

您不需要单独的按钮。只需调用模态('show')函数,如下所示,

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

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

所以你可以:

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

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

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

或者您甚至可以使用:

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