Parse Error escape PHP inside Jquery and PHP

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in ...

This is the error that I'm getting

<?php
      function my_custom_js() {
        echo " <script>" ;
        echo " jQuery(document).ready(function(){ 

    jQuery('#secondary-front .first h3').addClass('
     <?php $options = get_option('mytheme_theme_options'); 
     if(!empty($options['first_widget_icon'])) echo $options['first_widget_icon']?>    ');

    jQuery('#secondary-front .second h3').addClass('<?php $options =        get_option('mytheme_theme_options');
    if (!empty($options['second_widget_icon'])) echo $options['second_widget_icon'];?>');

    jQuery('#secondary-front .third h3').addClass('<?php $options =     get_option('mytheme_theme_options');
    if (!empty($options['third_widget_icon'])) echo $options['third_widget_icon'];?>');
    });  

    ";  
    echo "</script> ";
    }
    add_action('wp_head', 'my_custom_js');
?>

I cannot get this code to escape correctly, i have php > jquery > php


The problem is your quotes ( " ) don't weigh up on both sides. That said, when I've gone to investigate the problem, I've noticed worse things with your code, so I've rewritten it entirely for you:

<?php

    function my_custom_js() {
        $options = get_option('mytheme_theme_options'); 

        echo "<script>
            jQuery(document).ready(function(){
                jQuery('#secondary-front .first h3').addClass('" . ($options['first_widget_icon'] ?: NULL) . "');
                jQuery('#secondary-front .second h3').addClass('" . ($options['second_widget_icon'] ?: NULL) . "');
                jQuery('#secondary-front .third h3').addClass('" . ($options['third_widget_icon'] ?: NULL) . "');
            });
        </script>";
    }

    add_action('wp_head', 'my_custom_js');

?>

One thing I've done is moved $options = get_option('mytheme_theme_options'); to the top. I've also removed the repeated calls to this. Also, that's had the knock-on effect that the echo can be made all in 1 statement, with clever use of the ternary operator.

echo ($something ?: NULL); means if $something exists, echo it, else echo nothing.

Using the ternary operator with the ?: shorthand requires PHP >= 5.3.0

For versions below this, simply fill in the middle part, ie:

// PHP >= 5.3.0
($options['first_widget_icon'] ?: NULL)

// PHP < 5.3.0
($options['first_widget_icon'] ? $options['first_widget_icon'] : NULL)

Of course, the code might need tweaking to your liking, but it should be a basis for improvement.

链接地址: http://www.djcxy.com/p/12046.html

上一篇: 如何检测PHP中的语法错误?

下一篇: Parse Error在Jquery和PHP中转义PHP