jQuery SVG-object标记加载事件

Eur*_*uro 9 jquery object-tag onload-event

我有一个页面,通过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'
})
);
Run Code Online (Sandbox Code Playgroud)

我需要访问SVG文档(将一个变量"推"到svg脚本上下文中),但必须为此加载SVG.我的问题是我没有让load事件工作.没有显示警报.

怎么做?

编辑:似乎jQuery只是阻止将"加载"事件绑定到非图像或文档元素,所以我只使用"官方"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')
        })
    })
);
Run Code Online (Sandbox Code Playgroud)

Mat*_*yra -1

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

.load( url [, data] [, complete(responseText, textStatus, XMLHttpRequest)] )
Run Code Online (Sandbox Code Playgroud)

所以

grid.append($('<object>').load('image.svg',
    function (response, status, xhr) {
        if (status == 'success') {
            // yay the load is ok
            alert('loaded');
        }
    })
);
Run Code Online (Sandbox Code Playgroud)

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

更新:我还没有尝试使用 HTML 将 SVG 数据加载到浏览器中,但 W3C 文档没有提到该<object>标签可用于此目的。他们的例子使用<embed>

<embed src="circle1.svg" type="image/svg+xml" /> 
Run Code Online (Sandbox Code Playgroud)

你试过用它代替吗<object>

更新2:

我认为上述解决方案也不起作用,因为 JSonload事件由以下标签支持<body>, <frame>, <frameset>, iframe, <img>, <input type="image">, <link>, <script>, <style>- 我认为这就是 jQuery 所挂钩的内容,因此它只适用于这些元素。jQuery 文档说该对象支持事件处理images, scripts, frames, iframes程序window

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

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

更新3:

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

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

  2. 此处ajax()详细介绍了jQuery调用,包括有关加载后与 svg 画布交互的信息。