简体   繁体   English

在 JavaScript onClick 事件处理程序中转义双引号

[英]Escaping double quotes in JavaScript onClick event handler

The simple code block below can be served up in a static HTML page but results in a JavaScript error.下面的简单代码块可以在静态 HTML 页面中提供,但会导致 JavaScript 错误。 How should you escape the embedded double quote in the onClick handler (ie "xyz)? Note that the HTML is generated dynamically by pulling data from a database, the data of which is snippets of other HTML code that could have either single or double quotes. It seems that adding a single backslash ahead of the double quote character doesn't do the trick.您应该如何转义onClick处理程序中嵌入的双引号(即“xyz”)?请注意,HTML 是通过从数据库中提取数据动态生成的,其中的数据是其他 HTML 代码的片段,可以包含单引号或双引号. 似乎在双引号字符前添加一个反斜杠并不能解决问题。

<script type="text/javascript">
    function parse(a, b, c) {
        alert(c);
    }
</script>

<a href="#x" onclick="parse('#', false, '<a href=\"xyz'); return false">Test</a>

Did you try你试过了吗

&quot; or \\x22\\x22

instead of代替

\"

? ?

It needs to be HTML-escaped, not Javascript-escaped.它需要是 HTML 转义的,而不是 Javascript 转义的。 Change \\" to &quot;\\"更改为&quot;

While I agree with CMS about doing this in an unobtrusive manner (via a lib like jquery or dojo), here's what also work:虽然我同意 CMS 以一种不引人注目的方式(通过 jquery 或 dojo 之类的库)执行此操作,但以下内容也有效:

<script type="text/javascript">
function parse(a, b, c) {
    alert(c);
  }

</script>

<a href="#x" onclick="parse('#', false, 'xyc&quot;foo');return false;">Test</a>

The reason it barfs is not because of JavaScript, it's because of the HTML parser.它的原因不是因为 JavaScript,而是因为 HTML 解析器。 It has no concept of escaped quotes to it trundles along looking for the end quote and finds it and returns that as the onclick function.它没有转义引号的概念,它会沿着查找结束引号并找到它并将其作为 onclick 函数返回。 This is invalid javascript though so you don't find about the error until JavaScript tries to execute the function..这是无效的 javascript,所以在 JavaScript 尝试执行该函数之前,您不会发现错误。

您可能还想尝试使用两个反斜杠(\\\\")来转义转义字符。

I think that the best approach is to assign the onclick handler unobtrusively .我认为最好的方法是不引人注意地分配 onclick 处理程序。

Something like this:像这样的东西:

window.onload = function(){
    var myLink = document.getElementsById('myLinkId');
    myLink.onclick = function(){ 
        parse('#', false, '<a href="xyz');
        return false;
    }
}

//...


<a href="#" id="myLink">Test</a>

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

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