2019-05-11 20:31

无法在JS中添加PHP [重复]


This question already has an answer here:

I am trying to add a PHP code to echo a text inside of JavaScript but when I try the code it's don't echo the text it echoes 0

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");';} ?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dpjo15650 dpjo15650 2年前

    i had the same issue on past i did use php to print all javascript with php vars too , in your case it well be :

         echo "<script>";
         echo "window.onload = function(){";
         if (empty($dark_mode)){
                  echo "$('*').toggleClass('light') document.getElementById('*').classList.remove('dark');";
         echo "$('*').toggleClass('light') document.getElementById('*').classList.remove('light');";

    echo ""; ?>

    点赞 评论 复制链接分享
  • douxiajia6309 douxiajia6309 2年前

    I would prefer Heredoc syntax to echo multiple lines of dynamic JavaScript/jQuery code. You don't need to escape any quotes and it's easier to read, especially when you have dozens of lines of code.

    $if_script_code = <<<if_script
    Here goes the script code 
        for better readability
        and without the need to
        escape a ton of quotes.
    $else_script_code = <<<else_script
    more script code
    if ($my_condition === TRUE) {
        $script_code = $if_script_code;
    else {
        $script_code = $else_script_code;
    window.onload = function(){<?=$script_code?>;}

    PHP Manual: Heredoc

    点赞 评论 复制链接分享
  • doucong1853 doucong1853 2年前

    You have a syntax error with your quotes - there are several singlequotes that arent' escaped, so PHP suddenly gets an unexpected *.

    window.onload = function(){
        <?php if (empty($dark_mode)){ echo '$('*').toggleClass("light") 
     // -----------------------------------^^^^^^^ See the mismatch of quotes here
    document.getElementById("*").classList.remove("dark");';}else{ echo '$('*').toggleClass("light")  document.getElementById("*").classList.remove("light");';} ?>

    You can solve this a few ways, one is by using double-quotes or escaping the single quotes, but you can simplify this quite a bit by just setting a variable in PHP and using that instead of doing the same thing inside the conditions.

    window.onload = function(){
        // Remove both dark and light
        $("*").removeClass("dark light");
        // Add current mode based on $dark_mode in PHP
        $("*").addClass("<?php echo empty($dark_mode) ? 'light' : 'dark'; ?>");
    点赞 评论 复制链接分享