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

时间:2014-02-28 07:17:41

标签: javascript html

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

我试过了:

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

但由于引号没有嵌套而遇到问题。

因此,我尝试了:

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

但是,单引号不被接受。

3 个答案:

答案 0 :(得分:2)

你必须逃避内部引号

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

答案 1 :(得分:0)

您可以使用转义单引号,如下所示

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

答案 2 :(得分:0)

引号不会被转义,这意味着你的内部报价正在关闭第一个引号,使PHP混乱。

要逃避它,请使用内部单引号:

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