简体   繁体   English

jv在svg中的奇怪行为

[英]javascript in svg strange behavior

The following html code is working (Chrome 44, Firefox 37) : 以下HTML代码正常运行(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. svg文本标签'CLICK ME'甚至不可见。 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 使用您的浏览器,您可以看到这是如何解析的,在Chrome上我有这个结果

在此输入图像描述

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> 实际上这不是因为注释块/*而是因为在for循环中使用的<被解释为HTML <l.length>

You can use CDATA to avoid that HTML parser parse this piece of code 您可以使用CDATA来避免HTML解析器解析这段代码

 <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. 发生这种情况是因为此<script>元素不是HTML中定义的相同元素。 It also provide compatibility with browsers that do not support scripting language, so accoding to W3C it need to be escaped. 它还提供与不支持脚本语言的浏览器的兼容性,因此需要对W3C进行转义。

Because of coomments Should be so: http://jsfiddle.net/btux9s2d/3/ 因为coomments应该如此: 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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