javascript 将 onClick 操作放入 echo 语句的语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7162328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:08:52  来源:igfitidea点击:

Syntax for putting an onClick action in an echo statement

phpjavascriptgoogle-analyticsecho

提问by Eric

What would be the correct syntax for the onClick attribute in the following:

下面的 onClick 属性的正确语法是什么:

    <?php 

    if($_resp['user']) {

    echo '<div class="logo"><a href="http://www.example.com/" onClick="_gaq.push(['_trackEvent', 'Join', 'Home', 'BigButton']);">Link Text</a>';        

 }

    ?>

回答by Michael Berkowski

Since you are nesting both double and single quotes, you will need to escape the single quotes in the onClickwith backslashes.

由于您同时嵌套双引号和单引号,因此您需要onClick使用反斜杠对单引号进行转义。

echo '<div class="logo"><a href="http://www.example.com/" onClick="_gaq.push([\'_trackEvent\', \'Join\', \'Home\', \'BigButton\']);">Link Text</a>';

回答by Marc B

Consider using a HEREDOC

考虑使用 HEREDOC

if ($_resp['user']) {
   echo <<<EOL
<div class="logo"><a href="http://www.example.com/" onClick="_gaq.push(['_trackEvent', 'Join', 'Home', 'BigButton']);">Link Text</a>

EOL;
}

or dropping out of PHP mode:

或退出 PHP 模式:

if ($_resp['user']) { ?>
<div class="logo"><a href="http://www.example.com/" onClick="_gaq.push(['_trackEvent', 'Join', 'Home', 'BigButton']);">Link Text</a>

<?php }

Both get the job done, and eliminate any need to escape quotes inside the html/javascript you're generating

两者都完成了工作,并且无需在您生成的 html/javascript 中转义引号

回答by pimvdb

You can mix HTML and PHP, so you might want to simply move it out of PHP:

您可以混合使用 HTML 和 PHP,因此您可能只想将其从 PHP 中移出:

<?php 

if($_resp['user']) {

?>

<div class="logo"><a href="http://www.example.com/" onClick="_gaq.push(['_trackEvent', 'Join', 'Home', 'BigButton']);">Link Text</a>

<?       

}

?>