我在博客文章中使用 d3js 时遇到了问题。
我已经成功地完成了这样的安装
copy d3.min.js to /content/themes/[theme name]/assets/js/
并添加
<script src="{{asset "js/d3.min.js"}}" charset="utf-8"></script>
进入
/content/themes/[theme name]/default.hbs
顺便说一句:将其添加到 <head>
中非常重要部分!
和
如果我添加 <script>
在我的 Markdown 博客文章中,我没有得到任何预期的结果/操作
<script>
var svg = d3.select("#animviz")
.append("svg")
.attr("width", w)
.attr("height", h);
// some additional code you can find below
</script>
<div id="animviz">
</div>
我还尝试围绕这个 JS 编写自执行函数:
(function(){
// the hole code
})();
没有成功。
唯一有效的方法是包含 the hole code
在 Ghost-Settings->Code Injection->Blog Footer 中:
<script src="https://gist.githubusercontent.com/blablarnab/7621762/raw/0fc10237392911e12c4641c44cdd63066573430b/caterpillar.js"></script>
如果我添加目标 <div id="animviz"></div>
就可以了进入博客文章 Markdown。
有什么想法吗?我认为这是一个 Markdown 解析器问题。一个可能的解决方案是有一种方法将代码附加到博客文章的 DOM(博客页脚)并刷新代码。但如何呢? location.reload();
我想也会像 d3js 一样死掉吗?
最佳答案
解析器尝试执行博客文章本身中的代码。所以它会一步一步执行此操作。因为 JS 部分在您的帖子中排在第一位,所以没有有效的目标并且什么也没有发生。如果您将 console.log() 添加到代码中,您将看到它被执行 - 但不会进入目标,因为此时它不存在。
因此,您需要将目标设置为 <div id="animviz">
</div>
在<script>// your JS</script>
之前像这样:
<div id="animviz">
</div>
<script>
var svg = d3.select("#animviz")
.append("svg")
.attr("width", w)
.attr("height", h);
// some additional code you can find below
</script>
关于javascript - Ghost - 嵌入式 JavaScript 不会触发 d3js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31434204/