我需要一些关于此代码的帮助。我想阅读当前的网址,当网址中包含“#_ThankYou”时,我想在页面上添加一个新内容,并且该div包含一些将显示广告供应商广告的javascript。我有以下但我认为我可能陷入无限循环。不确定我是否正确编码。有人有好的建议吗?
<script type="text/javascript">
window.eddyCookieCount = 0;
window.eddyNumberAttempts = 0;
window.myInterval = setInterval(function() {
if (window.location.href.indexOf("#_ThankYou") > window.eddyCookieCount) {
jQuery('div.thankyou-container').append('<div>' + vm_load({
"displayId": "12584", // Numeric unique ad display Id
"publisherId": "33927", // Publisher ID
"campaign": "9380", // Numeric Publisher Campaign Id
"maxResults": "3",
"areaofstudy": JSON.parse(jQuery.cookie('CategorySubCategorySpecialty')).CATEGORIES[0].text.replace('Business','1').replace('Criminal Justice & Legal','3').replace('Education','5').replace('Fine Arts & Design','2').replace('Health & Medicine','8').replace('Liberal Arts & Humanities','5').replace('Math, Science & Engineering','9').replace('Public Affairs & Social Sciences','13').replace('Religious Studies','5').replace('Technology','9').replace('Vocational Training',''),
"md": "1"
}) + '</div>');
window.eddyNumberAttempts++;
if (window.eddyNumberAttempts > 60) {
window.eddyCookieCount = jQuery.cookie('CategorySubCategorySpecialty').length;
window.eddyNumberAttempts = 0;
}
}
else if (jQuery.cookie('CategorySubCategorySpecialty').length < window.eddyCookieCount) {
window.eddyCookieCount = jQuery.cookie('CategorySubCategorySpecialty').length;
}
}, 50);
</script>
答案 0 :(得分:4)
无需间隔来监视要添加的哈希值。
$(window).on('hashchange', function() {
if (window.location.search === "#_ThankYou") {
}
});
在您的代码中,当您处于更改URL的状态时,我看不到您取消间隔,因此它会继续触发。你需要取消它。
window.clearInterval(window.myInterval)
答案 1 :(得分:0)
它适用于我,我必须在视图更改时检查URL中的标记。
我的工作方式是在代码下面,这似乎不太好用,但它是基于选择器工作的:
$('.nav ul li a').click(function() {
setTimeout(changeurl, 4000);
});
function changeurl(title, newurl) {
if (window.location.hash == '') {
return window.location.hash = '#/dashboard';
}
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.hash;
if (history.pushState) {
window.history.pushState({path:newurl},'',newurl);
}
}
最后,我修改了代码:
var token = window.location.search;
$(window).on('hashchange', function() {
if (window.location.search === token) {
setTimeout(changeurl, 4000);
}
});