简体   繁体   English

使用javascript编写HTML时使用单引号

[英]Use of singlequotes when writing HTML using javascript

I have this code inside a php file: 我在php文件中有以下代码:

<script>

var myString = '{$data10}'; 
if (myString.charAt(0)) {
    document.write('<a target="_blank" 
                       href="https://www.somedomain.com/join?id={$data10}">
                    <img src="images/join-bim.png" width="300" height="74" 
                         onMouseOut="this.src="images/join-bim.png"" 
                         onMouseOver="this.src="images/join-bimB.png"" /></a>');
} else {
    document.write('<a target="_blank" 
                       href="https://www.somedomain.com/join?id=111111">
                    <img src="images/join-bim.png" width="300" height="74" 
                         onMouseOut="this.src="images/join-bim.png"" 
                         onMouseOver="this.src="images/join-bimB.png"" /></a>');
}
</script> 

I have tried: 我努力了:

onMouseOut="this.src="images/join-bim.png""

but encountered problems due to the quotes not nesting. 但是由于引号未嵌套而遇到问题。

Because of that, I then tried: 因此,我尝试了:

onMouseOut="this.src='images/join-bim.png'" 

However, the single quotes are not being accepted. 但是,单引号不被接受。

您必须转义内引号

onMouseOver="this.src=\"images/join-bimB.png\""

You can use escaped single quotes, as you can see below 您可以使用转义的单引号,如下所示

<script>
var myString = '{$data10}'; 
    if(myString.charAt(0)){
        document.write('<a target="_blank" href="https://www.somedomain.com/join?id={$data10}"><img src="images/join-bim.png" width="300" height="74" onMouseOut="this.src=\'images/join-bim.png\'" onMouseOver="this.src=\'images/join-bimB.png\'" /></a>');
    }
    else {
        document.write('<a target="_blank" href="https://www.somedomain.com/join?id=111111"><img src="images/join-bim.png" width="300" height="74" onMouseOut="this.src=\'images/join-bim.png\'" onMouseOver="this.src=\'images/join-bimB.png\'" /></a>'); 
    }
</script> 

The quotes are not escaped, meaning your quotes inside is closing the first quote, making PHP confused. 引号不会转义,这意味着您的引号将关闭第一个引号,使PHP感到困惑。

To escape it, use for your inner-single quotes: 要对其进行转义,请使用内单引号​​:

onMouseOver=\'this.src="images/join-bimB.png"\'

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

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