许多人为这个不太合理的标题道歉;我不知道如何描述这一点。建议将不胜感激。
我有这个脚本,Squarespace 将其注入网页上每个博客文章的页脚,以及博客条目的单个页面的页脚。在单个页面中加载时,代码执行得很好。但是,在每个博客条目加载一次的网页上,事情变得有点混乱。
这是代码:
<a name="comments-outer-wrapper" />
<a class="muut" href="https://muut.com/i/test/comments:test">Comments</a>
<script>
var mtitle = document.title.slice(0, -13);
var mhref = $("article").attr("id").substring(8);
var mcount = "//api.moot.it/postcounts?path=/test/comments:" + mhref;
$.getJSON(mcount, function(json) {
var results = $(".entry-actions");
$.each(json, function(key, val) {
results.prepend("<a class=\"entry-comments\" href=\"{permalink}#comments-outer-wrapper\" title=\"Comments\">" + val["size"] + " Comments</a>");
});
});
$(".muut").attr( "href","https://muut.com/i/test/comments:" + mhref);
$(".muut").attr( "title",mtitle);
</script>
我认为,当浏览器读取代码注入时,单个文章页面逐行发生的情况是脚本按预期执行。
但是,由于在博客摘要页面 Squarespace 每篇文章都会注入一次代码,我认为这就是导致问题的原因。代码执行 3、4、5 次,并且 .getJSON 函数的结果被附加到<a class="entry-comments">
每次执行的部分 - 最终发生的是:
“1 条评论”重复 3 次(页面上的每个博客条目一次)。此外,这些<a>
元素中的每一个的 HREF 都是相同的 URL,这向我表明,每个元素的var mtitle
、var mhref
和var mcount
都是相同的;在每个实例之间没有删除、刷新或未定义变量。
所以,在我原始的头脑中,我相信正在发生的事情是这样的:
[BLOG WEBPAGE]--[mtitle3]-[mhref3]-[mcount3]
|
|--[BLOG ARTICLE 1]--[SCRIPT]-[mtitle1]-[mhref1]-[mcount1]
|
|--[BLOG ARTICLE 2]--[SCRIPT]-[mtitle2]-[mhref2]-[mcount2]
|
|--[BLOG ARTICLE 1]--[SCRIPT]-[mtitle3]-[mhref3]-[mcount3]
仅使用最后收集的变量。
我想要发生的是这样的:
[BLOG WEBPAGE]
|
|
[MASTER SCRIPT]--[mtitleX]-[mhrefX]-[mcountX]
|
|--[BLOG ARTICLE 1]--[mtitle1]-[mhref1]-[mcount1]
|
|--[BLOG ARTICLE 2]--[mtitle2]-[mhref2]-[mcount2]
|
|--[BLOG ARTICLE 1]--[mtitle3]-[mhref3]-[mcount3]
我希望这不是太长或太模糊。