简体   繁体   中英

Use of singlequotes when writing HTML using javascript

I have this code inside a php file:

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

To escape it, use for your inner-single quotes:

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

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