简体   繁体   中英

javascript in svg strange behavior

The following html code is working (Chrome 44, Firefox 37) :

 <svg width="100" height="100"> <script> function test() { var l= [0,1,2,3]; console.log(l.length); } </script> <text x="20" y="20" onclick="test()">CLICK ME</text> </svg> 

but this is not :

 <svg width="100" height="100"> <script> function test() { var l= [0,1,2,3]; console.log(l.length); /*for (var i=0; i<l.length; i++) { console.log(i); }*/ } </script> <text x="20" y="20" onclick="test()">CLICK ME</text> </svg> 

The svg text tag 'CLICK ME' won't even be visible. And the only difference is commented code ! What is the problem ?

With your browser you can see how this is parsed, on Chrome I have this result

在此输入图像描述

Actually this is not because of the comment block /* but because of the < that is used in the for-loop that is interpreted as HTML <l.length>

You can use CDATA to avoid that HTML parser parse this piece of code

 <svg width="100" height="100"> <script><![CDATA[ function test() { var l= [0,1,2,3]; console.log(l.length); /*for (var i=0; i<l.length; i++) { console.log(i); }*/ } ]]></script> <text x="20" y="20" onclick="test()">CLICK ME</text> </svg> 

This happens because this <script> element is not exaclty the same element that is defined in HTML. It also provide compatibility with browsers that do not support scripting language, so accoding to W3C it need to be escaped.

Because of coomments Should be so: http://jsfiddle.net/btux9s2d/3/

<svg width="100" height="100">

<script>
    function test() {
        var l= [0,1,2,3];
        console.log(l.length);
       <!--for (var i=0; i<l.length; i++) {
            console.log(i);
        }-->
    }
</script>

<text x="20" y="20" onclick="test()">CLICK ME</text>

</svg>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM