Materialize.css 模态框未正确初始化动态创建的元素

Materialize.css Modal is Not Initializing Correctly on Dynamically Created Elements

我正在使用 ajax 调用将行动态附加到使用 jQuery 的 table。我希望在每一行中生成的按钮显示一个模式,其中包含特定于该特定行中的项目的数据。

我目前 运行 遇到以下问题:

-当我点击第一个和第二个按钮时出现模态。但是,当我尝试关闭第二个模态时,模态中的框阴影并没有消失,我无法再继续单击任何按钮,直到我刷新页面。

我查看了 Materialize.css 文档,它提到如果使用触发器显示模态,我们需要使用 $(".modal-trigger").leanModal() 初始化模态。我用来触发模式的 ID 在下面的代码中称为 "nutrition-facts"。

如有任何帮助,我们将不胜感激。谢谢!!

更新:使用 CodePen:http://codepen.io/mtaggart89/pen/pgbgOB

HTML:

<!-- Modal Structure -->
<div id="nutrition-facts" class="modal modal-fixed-footer">
  <div class="modal-content">
    <h4>Nutrition Facts</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">Close</a>
  </div>
</div>

jQuery 创建元素的函数:

function buildTable(foodData) {
  var itemList = foodData.list.item;
  var foodGroup, foodName, newDiv, createButton, ndbNumber, createTable, tableHead, categoryHeading, nameHeading, tr;
  $("table").addClass("bordered");
  categoryHeading = $("<th>").html("Category");
  nameHeading = $("<th>").html("Name");
  $("thead").append(categoryHeading).append(nameHeading);       
  for (var i = 0; i < itemList.length; i++) {
    foodGroup = $("<td>").html(itemList[i].group);
    foodName = $("<td>").html(itemList[i].name);
    ndbNumber = itemList[i].ndbno;
    newDiv = $("<td>");
    createButton = $("<a>")
                    .addClass("waves-effect waves-light btn cyan nutrition modal-trigger")
                    .attr("href", "#nutrition-facts")
                    .html("Nutrition Facts")
                    .attr('data-ndbnum', ndbNumber);
    addButton = newDiv.append(createButton);
    tr = $("<tr>").append(foodGroup).append(foodName).append(addButton);
    $("tbody").append(tr);
  }
}

jQuery 事件侦听器:

$(document).on('click', '.nutrition', function(e){
  e.preventDefault();
  var ndbNumber = $(this).attr('data-ndbnum');
  $(".modal-trigger").leanModal();
});

http://materializecss.com/modals.html

请将代码更改为

$(document).on('click', '.nutrition', function(e) {
    e.preventDefault();
    var ndbNumber = $(this).attr('data-ndbnum');
    //you have to trigger modal like this
    //$(".modal-trigger").leanModal();
    $('#nutrition-facts').openModal();
  });

http://codepen.io/anon/pen/YwWwdx