【问题标题】:Interact with Dynamically generated content in $(document).ready与 $(document).ready 中动态生成的内容交互
【发布时间】:2019-03-02 12:15:14
【问题描述】:

我在与 $(document).ready 中动态生成的内容交互时遇到问题。

我正在开发一个动态生成大量内容的 web 应用程序。我正在使用 Nodejs 和 Jquery。在 $(document).ready 中,我调用了一个读取数据库、生成许多列表项并将它们附加到文档的填充函数。这现在工作得很好。我遇到问题是因为我还希望每个列表项在模式框中都有更详细的视图,可以通过单击列表项或 url 中的哈希来访问。为了避免对服务器的更多调用,每个列表项都有一个隐藏字段,用于存储要放入模式框中的信息。所以转到 url/#foo 会加载页面,找到 id 为 #foo 的项目,设置模态框,并立即显示模态框。

$(document).ready(function() {
    // Populate the list on initial page load
    populateList(); //Reads from database, uses template to create list    item elements, and appends to document with .appendchild.

    // Grab the modal box
    var modal = document.getElementById('ModalView');

    // if there is a hash, scroll to that location, and modify and show    the modal box for that item.
    if(location.hash){
        //    Find the matching list item, get the info
        var infoString =  document.getElementById(location.hash).info; 
        // Code to modify modal box based on infoString goes here
        modal.style.display = "block"; // Show Modal box
    }

这不起作用,因为 .getElementByID(location.hash) 总是返回 null。这不是因为 id 不匹配,我彻底检查了。如果我理解正确,问题是我的列表项在 $(document).ready 之后才完全是文档的一部分,这意味着我不能使用 getElementById。有没有办法让我从 $(document).ready 中的列表项中获取模式框的信息?还是在页面加载时?

编辑:已解决。我制作了一个用于创建模态框的函数,并将其放在 AJAX 函数中。

【问题讨论】:

  • 你能显示populateList的代码吗

标签: javascript jquery html


【解决方案1】:

$(document).ready 内部,您将可以访问在初始页面加载时加载的所有 dom 元素,那里一切正常。

问题似乎是populateList 是异步的,并且在该函数完成并附加它们之前元素不会准备好。

一个简单的方法是向populateList函数传递一个回调,然后在http请求成功时调用它:

function populateList(callback) {
  // ..
  $.get('some-url').success(function() {
    // once you get a successful http response, call the callback:
    callback();
  });
}

那么你就可以得到添加后的id了:

$(document).ready(function() {

  populateList(function() {
    if (location.hash) {
      var infoString =  document.getElementById(location.hash).info; 
      modal.style.display = "block"; // Show Modal box
    }
  });

【讨论】:

    【解决方案2】:

    一旦文档准备好,您就开始填充您的列表,这意味着在您populateList 时,数据仍然不存在,因此还没有包含您的位置哈希的元素。您可以使用jQuery.when 等到数据存在并开始操作它。

    function modifiyLocationHash() {
      var modal = document.getElementById('ModalView');
      var infoString =  document.getElementById(location.hash).info; 
      modal.style.display = "block";
    }
    $(document).ready(function() {
       $.when(populateList()).then(modifyLocationHash());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-20
      • 2011-04-07
      • 2011-07-19
      相关资源
      最近更新 更多