在javascript "if"中错误使用php


Wrong usage of php in a javascript "if"?

我正在尝试根据访问者屏幕大小自动切换wordpress中的背景图像。如果他/她有一个大屏幕,他/她得到大版本的图像。如果屏幕小,他/她会得到较小的版本。(只是为了减少装载时间。之后图像将被调整大小以填充屏幕,但这已经工作了。

不起作用的是检查小版本是否存在。如果它不存在,脚本应该退回到更大的版本,并只使用该图像。我得到一个背景图像,但它只是一个大的(wordpress字段名"BG_value")。小图像的url存储在"BG_value-medium"中)。

图像确实存在,并且通过wordpress字段的路径也很好,所以这不是问题。:/

但是,话不多说,我给你的代码(从我的header.php从wordpress)。

<body>
<!-- Wordpress Loop -->
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
        <script type="text/javascript">
        if (($(window).width() < 1340) && (<?php 
                                                if(file_exists(bloginfo('template_url').get_post_meta($post->ID, 'BG_value-medium', $single = true))){
                                                    echo "true";
                                                }else{
                                                    echo "false"; } ?> )){
            <?php $bgimg = get_post_meta($post->ID, 'BG_value-medium', $single = true); ?>
        } else {
            <?php $bgimg = get_post_meta($post->ID, 'BG_value', $single = true); ?>
        }
        </script>
    <div id="bgimage"> <img class="stretch" src="<?php bloginfo('template_url'); ?><?php echo $bgimg; ?>" alt="" /> </div>
<?php endwhile; endif; ?>

如果这看起来有点乱,我很抱歉,我已经做了几个小时了,一遍又一遍地修改。

你知道这里出了什么问题吗?查看页面

你在这里有一个很大的逻辑错误。你想用javascript函数设置bg图像,但你从来没有尝试用javascript设置它,只使用php echo。在浏览器中查看一下这个javascript片段的源代码,你就会明白我的意思了。

你应该在thenelse的javascript变量中存储图像路径,并使用它们来设置bg图像。

未经测试:

<script type="text/javascript">
    if (($(window).width() < 1340) && (<?php if(file_exists(bloginfo('template_url').get_post_meta($post->ID, 'BG_value-medium', $single = true)))){
                                                echo "true";
                                             }else{
                                                echo "false"; } ?> )){
        var bgimage="<?php echo get_post_meta($post->ID, 'BG_value-medium', $single = true); ?>";
    } else {
        var bgimage="<?php echo get_post_meta($post->ID, 'BG_value', $single = true); ?>";
    }
    document.getElementById("bgimageimg").src=bgimage;
</script>
<div id="bgimage"><img id="bgimageimg" class="stretch" src="" alt="" /></div>

我已经试着清理这些混乱,看看发生了什么。下面的代码是未经测试的,但是如果有些东西不工作,你现在至少可以知道为什么它不工作了。

<?php
if (have_posts()) {
    while (have_posts()) {
        the_post();
        echo '<script type="text/javascript">';
        $url = bloginfo('template_url');
        $img = get_post_meta($post->ID, 'BG_value-medium', $single = true);
        $file_exists = 'false';
        if (file_exists($url.$img)) {
            $file_exists = 'true';
        }
        echo 'var bgimg = '.get_post_meta($post->ID, 'BG_value', $single = true).';';
        echo 'if ($(window).width() < 1340 && '.$file_exists.') {';
        echo '  bgimg = '.get_post_meta($post->ID, 'BG_value-medium', $single = true).';';
        echo '}';
        echo '$("#bgimage").attr("src", bgimg);';
        echo '</script>';
    }
}
?>