14

我想将 JavaScript 代码添加到我的Tumblr博客上的每个单独的帖子页面。我有以下内容,但它似乎永远不会出现在任何页面上,更不用说永久链接或单个帖子页面了。我在这里尝试了许多变体,删除Posts块或PermalinkPage块无济于事。我在这里做错了什么?

<!-- Start JS -->
{block:Posts}
    {block:PermalinkPage}
    <script type='text/javascript'>
    __config = {
            {block:Date},date:'{Year}-{MonthNumberWithZero}-{DayOfMonthWithZero} {24HourWithZero}:{Minutes}:{Seconds}'{/block:Date}
            {block:PostSummary},title:{JSPlaintextPostSummary}{/block:PostSummary}
            {block:HasTags},tags:[{block:Tags}'{Tag}', {/block:Tags}],{/block:HasTags}
            ,url:'{URLEncodedPermalink}'
    };
    (function(){
      var s = document.createElement('script');
      s.type = 'text/javascript';
      s.src = document.location.protocol + '//example.com/example.js';
      (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(s);
    })();
    </script>
    {/block:PermalinkPage}
{/block:Posts}
<!-- END JS -->
4

2 回答 2

9

这就是我使用 JavaScript/前端解决它的方法。

var path = document.location.pathname;
path = path.split("/")[1]; // Should return the primary directory
path = path.toLowerCase(); // This should catch your.tumblr.com/Search and your.tumblr.com/search
if(path === "" || path === "search")){
    console.log('Index or Search page');
}else{
   // Run your function here
}

基本上,如果路径 URL 为空或等于,search则不运行该函数,但在任何其他情况下运行该函数。

然而,正如我所提到的,这并不是 100% 稳健的。由于路径可能是http://your.tumblr.com/#并且函数将失败,因此您可能必须构建更明确的逻辑(您可以说 ifpath !== " "为空字符串)。

我仍然不确定为什么在每一页上都有这个不是一个好主意。除非用户确实被链接到网站上的页面,而这些页面并没有通过索引页面进行路由。除非你的 JavaScript 代码很大,否则它都可以从索引页面缓存(但在热链接等情况下仍然可以从所有其他页面获得)。

编辑

根据下面的评论,我在一个测试 Tumblr 帐户上创建了一个基本示例。

代码如下所示:

  var path = document.location.pathname;
  path = path.split("/")[1];
  path = path.toLowerCase();
  if(path === "" || path === "about"){
    $('body').css('background','#F09');
    console.log('Index or about page');
  }else{
    $('body').css('background','#FC0');
    console.log('Other page');
  }

我正在使用的 Tumblr 页面在这里:http ://sg-test.tumblr.com/

(我认为没有搜索页面,搜索功能是您在模板中插入或激活的块,并且在每个页面上都可用。)

该函数主要检查索引页面(空的主目录)或关于页面(如果需要,将其替换为“搜索”或其他页面)。

控制台日志将在每个页面上输出。如果路径匹配索引或关于我已将正文颜色设置为粉红色,否则每隔一页将是橙色。

http://sg-test.tumblr.com/about(粉红色背景)

http://sg-test.tumblr.com/post/134796799695/post-title(橙色背景)

按照这个逻辑,如果函数满足路径变量要求,应该很容易调整函数来执行代码,就像我的第一个例子一样。

正如我所提到的,尽管http://sg-test.tumblr.com/#存在问题。这实际上仍然是索引页面,但我们的测试对于空目录返回 false,即使 Tumblr 将其映射到主页。

于 2016-08-11T14:51:28.657 回答
-3

我把它塞进了我的沙盒博客,看看可能是什么问题,当我检查 JS 控制台时,这是一个前额拍板。

{block:Date},date:

删除之前的逗号date,它应该可以工作。如果您有更多问题,请告诉我。

于 2016-08-12T16:41:11.703 回答