繁体   English   中英

jv在svg中的奇怪行为

[英]javascript in svg strange behavior

以下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> 

但这不是:

 <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> 

svg文本标签'CLICK ME'甚至不可见。 唯一的区别是注释代码! 问题是什么 ?

使用您的浏览器,您可以看到这是如何解析的,在Chrome上我有这个结果

在此输入图像描述

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

您可以使用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> 

发生这种情况是因为此<script>元素不是HTML中定义的相同元素。 它还提供与不支持脚本语言的浏览器的兼容性,因此需要对W3C进行转义。

因为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