Jquery和PHP内部的解析错误转义PHP


Parse Error escape PHP inside Jquery and PHP

分析错误:语法错误,意外的"(T_ENCAPSED_AND_WHITESPACE(,中应包含标识符(T_STRING(、变量(T_variable(或数字(T_NUM_STRING(。。。

这是我得到的错误

<?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');
?>

我无法使此代码正确转义,我有php>jquery>php

问题是你的报价("(不平衡。也就是说,当我去调查这个问题时,我注意到你的代码有更糟糕的地方,所以我完全为你重写了它:

<?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');
?>

我所做的一件事是将$options = get_option('mytheme_theme_options');移到顶部。我也删除了重复的呼吁。此外,通过巧妙地使用三元运算符,echo可以在一个语句中生成。

echo ($something ?: NULL);的意思是如果$something存在,则回显它,否则不回显

使用?:简写的三元运算符需要PHP>=5.3.0

对于低于此值的版本,只需填写中间部分,即:

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

当然,代码可能需要根据您的喜好进行调整,但它应该是改进的基础。