开发者

How to add JavaScript onClick handler to an embedded html object?

I'm trying to add an onClick handler to an embedded object. The handler needs to execute a function which is in an external .js file which is linked to the c开发者_C百科urrent html file via <script src="....

Do I need to reference the function differently due to it being located elsewhere?

Here is the code as it currently stands (which does not work, but also does not produce any errors):

<embed src="svg/button.svg" id="buttonEmbed" width="95" height="53" 
type="image/svg+xml" onClick="buttonEvent('buttonClicked')"/>


You have to implement onclick inside the svg and link it to the external JavaScript function using javascript inside the svg. See the SVG wiki for examples.

Update: Apparently the SVG wiki is no more. No surprise that the best references I can now (quickly) find are on StackOverflow itself.

This answer describes how to implement onclick inside the svg.


Use either javascript binding (Mario Menger answered that already).

If you can't or won't use the binding, you can use what xil3 answered with one modification:

Use an empty anchor tag <a href="javascript:someFunc()"></a> as the click consumer. Set it's z-index and position/size so it positioned over the svg object (for cross-browser compatibility).


If you wanted to call a method from the embedded object you could do something like this, Have the following as your embedsrc.html:

    <img src="svg/button.svg" width="95" height="53" 
    onClick="window.parent.buttonEvent('buttonClicked')"/>

and then have this in your main html:

    <embed src="embedsrc.html" width="95" height="53"> </embed>

    <script type='text/javascript'>
    function buttonEvent(input){alert(input);}
    </script>


Onclick should all be lowercase.

<embed src="svg/button.svg" id="buttonEmbed" width="95" height="53" 
type="image/svg+xml" onclick="alert('hello!');"/>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜