这是我的设置:
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的
因此,到目前为止,布局如下:
网页
<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
$(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,而不需要手动告诉程序何时运行它?
发布于 2016-03-24 08:26:31
如果您知道要查找哪些元素,则可以使用MutationObserver如下
//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);
})<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element"></div>
<div id="log"></div>
https://stackoverflow.com/questions/36159412
复制相似问题