无法在JS内添加PHP

我正在尝试添加一个PHP代码以在JavaScript内部回显文本,但是当我尝试该代码时却没有回显该文本,因此它回显0


<script>

window.onload = function(){

    <?php if (empty($dark_mode)){ echo '$('*').toggleClass("light") document.getElementById("*").classList.remove("dark");';}else{ echo '$('*').toggleClass("light")  document.getElementById("*").classList.remove("light");';} ?>

};

</script>


POPMUISE
浏览 170回答 3
3回答

繁花如伊

您的引号存在语法错误-arent逸出了多个单引号,因此PHP突然出现意外情况*。<script>window.onload = function(){&nbsp; &nbsp; <?php if (empty($dark_mode)){ echo '$('*').toggleClass("light")&nbsp;&nbsp;// -----------------------------------^^^^^^^ See the mismatch of quotes heredocument.getElementById("*").classList.remove("dark");';}else{ echo '$('*').toggleClass("light")&nbsp; document.getElementById("*").classList.remove("light");';} ?>};</script>您可以通过几种方法解决此问题,一种方法是使用双引号或转义单引号,但是您可以通过在PHP中设置一个变量并使用该变量而不是在条件内执行相同的操作来简化此操作。<script>window.onload = function(){&nbsp; &nbsp; // Remove both dark and light&nbsp; &nbsp; $("*").removeClass("dark light");&nbsp; &nbsp; // Add current mode based on $dark_mode in PHP&nbsp; &nbsp; $("*").addClass("<?php echo empty($dark_mode) ? 'light' : 'dark'; ?>");};</script>

慕姐4208626

我希望Heredoc语法可以回显多行动态JavaScript / jQuery代码。您无需转义任何引号,并且更容易阅读,尤其是当您有数十行代码时。$if_script_code = <<<if_scriptHere goes the script code&nbsp;&nbsp; &nbsp; for better readability&nbsp; &nbsp; and without the need to&nbsp; &nbsp; escape a ton of quotes.if_script;$else_script_code = <<<else_scriptmore script codehere...else_script;if ($my_condition === TRUE) {&nbsp; &nbsp; $script_code = $if_script_code;&nbsp; &nbsp; }else {&nbsp; &nbsp; $script_code = $else_script_code;&nbsp; &nbsp; }?><script>window.onload = function(){<?=$script_code?>;}</script>

弑天下

我过去也有同样的问题,我也确实使用php来用php vars打印所有的javascript,在您的情况下,它很可能是:&nbsp; &nbsp; &nbsp;<?php&nbsp; &nbsp; &nbsp;echo "<script>";&nbsp; &nbsp; &nbsp;echo "window.onload = function(){";&nbsp; &nbsp; &nbsp;if (empty($dark_mode)){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo "$('*').toggleClass('light') document.getElementById('*').classList.remove('dark');";&nbsp; &nbsp; &nbsp;}else{&nbsp;&nbsp; &nbsp; &nbsp;echo "$('*').toggleClass('light') document.getElementById('*').classList.remove('light');";&nbsp; &nbsp; &nbsp;}回显“”;?>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript