当我从PHP中回显时,jQuery无法正常工作

问题描述:

在php脚本的某些部分中,我只需要运行一些js,出于测试目的,我注释掉了php,因此在这里不再显示.

I need only some js to run during some parts of a php script, for testing purposes I commented out the php so I am not going to show it here.

<!DOCTYPE HTML>
<html>
<head>
    <script src="jquery-1.9.1.min.js" type="text/javascript"></script>
</head>
<body>
    <?php
        echo '<script>
        var width = $(window).width();<---Not working down too 1A
        var height = $(window).height();
        var widthSTR = width.toString();
        widthSTR = widthSTR.concat("px");
        var heightSTR = height.toString();
        heightSTR = heightSTR.concat("px");
        heightSTR = " ".concat(heightSTR);
        var size = widthSTR.concat(heightSTR);
        $("body").css({
            "background-size" : size, <---1A and above ^
            "background" : "url(p.jpg) 50% 0 no-repeat fixed"<---1B
        });
        </script>
        ';
    ?>
</body>
</html>

我标记为1B的行效果很好,显示背景图像.标为不工作"的部分似乎没有任何效果,但是当我在php之外的Script标记中单独运行它时,效果很好.知道为什么/错过了很多错误吗?预先感谢.

The line I have labeled 1B works fine, the background image displays. The section labeled not working seems to have no effect but when I run it separately in a Script tag outside of the php it works fine. Any idea why/huge mistakes I missed? Thanks in advance.

如果完整的dom依赖于要加载的对象,宽度等的大小,则应在加载完完整的dom后执行您的代码.

Your code should be executed once the full dom has been loaded if it depends on the objects being loaded, which width etc will do.

<!DOCTYPE HTML>
<html>
<head>
    <script src="jquery-1.9.1.min.js" type="text/javascript"></script>
</head>
<body>
    <?php
        echo '<script>
        $(document).ready(function(){
            var width = $(window).width();<---Not working down too 1A
            var height = $(window).height();
            var widthSTR = width.toString();
            widthSTR = widthSTR.concat("px");
            var heightSTR = height.toString();
            heightSTR = heightSTR.concat("px");
            heightSTR = " ".concat(heightSTR);
            var size = widthSTR.concat(heightSTR);
            $("body").css({
                "background-size" : size, <---1A and above ^
                "background" : "url(p.jpg) 50% 0 no-repeat fixed"<---1B
            });
        });
        </script>
        ';
    ?>
</body>
</html>

尽管我没有理由仍然需要回显字符串?为什么不直接在回声的HTML内直接包含实际的Javascript?

Although I no reason why you even need to echo out the string anyway? Why not just include the actual Javascript directly inside the HTML with the echo?