物化模态不起作用

Aja*_*rni 13 javascript jquery materialize

我为物化模态写了一个简单的代码.
HTML代码:

<a class="waves-effect waves-light btn view" data-target="modal1">View Scores</a>
<!-- Modal Structure -->
<div id="modal1" class="modal">
  <div class="modal-content">
    <h4>Modal Header</h4>
    <p>A bunch of text</p>
  </div>
  <div class="modal-footer">
    <a href="#!" class=" modal-action modal-close waves-effect waves-green btn-flat">Agree</a>
  </div>
</div>  
Run Code Online (Sandbox Code Playgroud)

JS代码:

$(document).ready(function() {
  // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
  /*$('.view').click(function (){
    $('#modal1').modal('open'); 
    alert('edskjcxnm');
  });*/
  /*$('.view').leanModal();*/
  $('#modal1').modal('open');
});  
Run Code Online (Sandbox Code Playgroud)

JSFiddle链接:https://jsfiddle.net/7f6hmgcf/
为什么不工作?

Ale*_*xey 28

首先初始化所有模态. $('.modal').modal();

完整的代码将如下所示

(function ($) {
    $(function () {

        //initialize all modals           
        $('.modal').modal();

        //now you can open modal from code
        $('#modal1').modal('open');

        //or by click on trigger
        $('.trigger-modal').modal();

    }); // end of document ready
})(jQuery); // end of jQuery name space
Run Code Online (Sandbox Code Playgroud)


小智 6

不是 100% 确定您在这里要求的是什么,但是如果您要问的是如何在按钮单击时触发模态,您可以通过设置这样的 onclick 来简单地做到这一点:

<a class="waves-effect waves-light btn view" onclick="$('#modal1').modal('open');">View Scores</a>
Run Code Online (Sandbox Code Playgroud)

但在你可以做 $('#modal1').modal('open'); 之前 您需要在 js 中启动模态,如下所示:

$(document).ready(function() {
    $('#modal1').modal();
});
Run Code Online (Sandbox Code Playgroud)

您可以在这个小提琴中查看我的解决方案:https : //jsfiddle.net/AndreasMolle/7f6hmgcf/13/

另一种解决方案可能是这样做:

$(document).ready(function() {
    $('#modal1').modal();
});
Run Code Online (Sandbox Code Playgroud)