这是我的设置:
product-shift.js
的脚本中加载。然后,该网页还使用jQuery将content.html
加载到网页上的元素中。 (我这样做,所以我不必使用愚蠢的CMS文本编辑器,因为它很糟糕)product-shift.js
应该使用content.html
的内容并将某些元素添加到网页中。截至目前,当用户点击适合我当前目的的东西时,我会触发此设置。但是,如果我想让我们说在网址中使用查询字符串告诉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>
1}}?
截至目前,布局如下:
$(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
自动调用{{1}}而无需手动告诉程序何时运行它?
答案 0 :(得分:2)
如果您知道要查找的内容,则可以使用MutationObserver之类的
// Hide Header on scroll down
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('#fixed header').outerHeight();
$(window).scroll(function(event){
didScroll = true;
});
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 250);
function hasScrolled() {
var st = $(this).scrollTop();
// Make sure they scroll more than delta
if(Math.abs(lastScrollTop - st) <= delta)
return;
// If they scrolled down and are past the navbar, add class .nav-up.
// This is necessary so you never see what is "behind" the navbar.
if (st > lastScrollTop && st > navbarHeight){
// Scroll Down
$('#fixed header').removeClass('nav-up').addClass('nav-down');
} else {
// Scroll Up
if(st + $(window).height() < $(document).height()) {
$('#fixed header').removeClass('nav-down').addClass('nav-up');
}
}
lastScrollTop = st;
}
&#13;
//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);
})
&#13;