【发布时间】:2019-05-29 03:41:39
【问题描述】:
我有一个相当复杂和特殊的问题。我有一个 div 容器,它最初是隐藏的 (display: none),当用户单击按钮时会显示它(使用 jQuery 函数 show())。在这个 div 中是一个 svg 可视化。
HTML
<div id="parent">
<object id='myObject' type="image/svg+xml"></object>
</div>
Javascript
我正在使用以下代码加载 SVG vis:
fetch('LINK TO THE SVG FILE')
.then(function(r) {return r.blob()})
.then(function(b) { return myObject.data = URL.createObjectURL(b)})
myObject.onload = function() { // wait for the svg has loaded
var myObject = this; // we're in the object's load event handler.
var svg = d3.select(myObject.contentDocument) // get the contentDocument
.select("svg"); // then get the svg inside
//...some more styling things happen here
}
我的问题是,我不知道如何(又名 where)我应该取消绑定 onload 事件,因为每次用户单击按钮以更改 display 模式时都会触发它父母div。当我使用以下代码时...
fetch('LINK TO THE SVG FILE')
.then(function(r) {return r.blob()})
.then(function(b) { return myObject.data = URL.createObjectURL(b)})
.then(function() {return myObject.onload = null})
...它从不应用我在onload 函数中执行的样式设置。此外,当我将myObject.onload = null 设置添加到按钮单击事件的末尾时,它不会触发onload 函数。
我在这里错过了什么?
【问题讨论】:
-
为什么需要 onload 处理程序?为什么不直接在 fetch 中添加另一个
.then(),它将在 Promise 解决后执行,即一旦 SVG 被加载? -
我做到了,如我在帖子第二部分中写下的解决方案所示。但是,我发现,我不能取消绑定
onload,因为每次显示父div时都需要加载 SVG,否则它将没有样式。我只是将 SVG 内联添加到我的 html 中,而不使用“显示:无”方法
标签: javascript d3.js svg onload unbind