jQuery SVG-object标记加载事件

我有一个页面,通过jQuery动态地将SVG添加到页面:

grid.append($('') .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。 我的问题是我没有让load事件工作。 没有显示警报。

怎么做?

编辑:似乎jQuery只是阻止将“加载”事件绑定到非图像或文档元素,所以我只使用“官方”addEventListener()函数(不支持愚蠢的IE,但这不是问题为了我):

 grid.append($('') .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(px), top: Math.round(py) }).each(function (i){ this.addEventListener ('load', function (e) { alert('loaded') }) }) ); 

我不知道你的例子中有什么grid ,但如果它是普通的dom元素,那么load api调用应该是api文档中定义的格式。 目前,您似乎正在尝试加载一个没有任何意义的函数调用。

 .load( url [, data] [, complete(responseText, textStatus, XMLHttpRequest)] ) 

所以

 grid.append($('').load('image.svg', function (response, status, xhr) { if (status == 'success') { // yay the load is ok alert('loaded'); } }) ); 

http://api.jquery.com/load/

更新:我没有尝试使用HTML将SVG数据保存到浏览器中,但是W3C文档没有提到可以使用标记。 他们的例子使用

  

你尝试过使用它而不是吗?

更新2:

我不认为上述解决方案也可以工作,因为JS onload事件由以下标记, , , iframe, , , , - 我认为这是jQuery挂钩的内容,因此它只适用于那些元素。 jQuery文档说,事件处理程序由images, scripts, frames, iframeswindow对象支持。

所以如果这不起作用,那么我想你只需要使用.load()方法调用并处理结果。 也许你可以把svg embed标签放到单独的html文件中,或者有一个生成html嵌入的脚本。

http://www.w3schools.com/jsref/event_onload.asp

更新3:

这个问题似乎至少有两个正确的解决方案。

  1. jQuery SVG插件http://keith-wood.name/svg.html

  2. 这里详细介绍了一个jQuery ajax()调用,包括有关在加载后与svgcanvas交互的信息。