我有一个页面,它通过 jQuery 动态地将 SVG 添加到页面:
grid.append($('<object>')
.load(function () {
// do stuff
alert('loaded')
})
.attr({
id: 'tile',
type: 'image/svg+xml',
width: Math.round(tile_w),
height: Math.round(tile_h),
data: 'map/base.svg'
})
);
我需要访问 SVG 文档(将变量“推送”到 svg 脚本上下文中),但必须为此加载 SVG。我的问题是我没有让加载事件正常工作。不显示任何警报。
怎么办?
编辑:看起来 jQuery 只是阻止将“加载”事件绑定(bind)到非图像或文档元素,所以我只使用“官方”addEventListener() 函数(而不是由愚蠢的 IE 支持,但这对我来说不是问题):
grid.append($('<embed>')
.attr({
id: 'tile' + i,
type: 'image/svg+xml',
width: Math.round(tile_w),
height: Math.round(tile_h),
src: 'map/base.svg'
})
.css({
position: 'absolute',
left: Math.round(p.x),
top: Math.round(p.y)
}).each(function (i){
this.addEventListener ('load', function (e) {
alert('loaded')
})
})
);
最佳答案
我不知道什么grid
在你的例子中,但如果它是一个普通的 dom 元素,那么 load
api 调用应采用 api 文档中定义的格式。目前看来您正在尝试加载一个没有任何意义的函数调用。
.load( url [, data] [, complete(responseText, textStatus, XMLHttpRequest)] )
所以
grid.append($('<object>').load('image.svg',
function (response, status, xhr) {
if (status == 'success') {
// yay the load is ok
alert('loaded');
}
})
);
更新:我还没有尝试使用 HTML 将 SVG 数据加载到浏览器中,但 W3C 文档没有提到 <object>
标签可以用于此目的。他们的示例使用 <embed>
<embed src="circle1.svg" type="image/svg+xml" />
您是否尝试过使用它来代替 <object>
?
更新2:
我认为上述解决方案也不起作用,因为 JS onload
事件由以下标签支持 <body>, <frame>, <frameset>, iframe, <img>, <input type="image">, <link>, <script>, <style>
- 我认为这就是 jQuery 所 Hook 的,因此它只适用于这些元素。 jQuery 文档说 images, scripts, frames, iframes
支持事件处理程序。和 window
对象。
所以,如果这确实不起作用,那么我想您只需要使用 .load()
方法调用并处理结果。也许您可以将 svg 嵌入标签放入单独的 html 文件中,或者使用一个生成 html 嵌入的脚本。
http://www.w3schools.com/jsref/event_onload.asp
更新3:
这个问题似乎至少有两个正确的解决方案。
jQuery SVG 插件 http://keith-wood.name/svg.html
一个 jQuery
ajax()
详情请调用here包括有关交互的信息 加载后使用 svg Canvas 。
关于jQuery SVG-对象标签加载事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12133181/