首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在动态加载的元素上执行函数

在动态加载的元素上执行函数
EN

Stack Overflow用户
提问于 2016-03-22 16:03:29
回答 1查看 2.5K关注 0票数 3

这是我的设置:

  • 网页-做两件事:加载一个名为product-shift.js的脚本。然后,该网页还使用jQuery将content.html加载到网页上的元素中。(我这样做是为了不需要使用愚蠢的CMS文本编辑器,因为它太烂了)
  • product-shift.js应该获取content.html的内容并将某些元素添加到网页中。到目前为止,当用户单击为我的当前目的工作的东西时,我已经启动了这个设置。但是,如果我想使用url中的查询字符串来告诉product-shift.js显示特定的产品,我想不出有任何方法可以做到这一点,而不将其硬编码到我的网页中的jQuery .load() callback中。

如何在product-shift.js中包含所有脚本操作,并且仍然能够判断何时完成content.html加载,即使product-shift.js不是加载content.html

因此,到目前为止,布局如下:

网页

代码语言:javascript
复制
<script type="text/javascript" src="product-shift.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $('#element').load('content.html', function(){
            //LOAD CALLBACK
            //In order for initializeElements() to run on content load it needs
            //to be called from here
        });
    });
</script>

Product-Shift.js

代码语言:javascript
复制
$(document).ready(function(){
    initializeElements() //This runs before Content.html is loaded so it doesn't do anything
});

$(document).on('click', '.elementOfContentHTML', function(){
    if(someElement does not exist) initializeElements();

    run rest of click event
});

var initializeElements = function(){
    //Add some elements to the web page based on Content.html
}

那么,是否有一种方法可以自动从initializeElements()调用product-shift.js,而不需要手动告诉程序何时运行它?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-24 08:26:31

如果您知道要查找哪些元素,则可以使用MutationObserver如下

代码语言:javascript
复制
//In the product list page
var target = document.querySelector('#element');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    //check whether our target element is loaded
    if ($(mutation.addedNodes).is('#child')) {
      //call the initializer
      $('#log').append('<div>Initialize</div>')

      //no need to observe further
      observer.disconnect();
    }
  });
});

// configuration of the observer:
var config = {
  childList: true
};

// pass in the target node, as well as the observer options
observer.observe(target, config);



//in the main page
jQuery(function() {
  //to simulate the ajax request
  setTimeout(function() {
    $('#log').append('<div>add</div>')
    $('#element').append('<div id="child">a</div>');
  }, 1000);
})
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element"></div>

<div id="log"></div>

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36159412

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档