当我从PHP回应它时,jQuery无法正常工作

我只需要在PHP脚本的某些部分运行一些js,为了测试目的,我注释掉了php,所以我不会在这里显示它。

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

我标记为1B的行正常工作,显示背景图像。 标记为不起作用的部分似乎没有效果,但是当我在php之外的Script标签中单独运行它时它可以正常工作。 知道为什么/我错过了巨大的错误? 提前致谢。

如果加载了完整的dom,你的代码应该被执行,如果它取决于正在加载的对象,宽度等等。

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

虽然我没有理由你甚至需要回声出弦? 为什么不直接在HTML中包含实际的Javascript和echo?

将代码包装在内:

 jQuery(function($) { // Put your whole code here }); 

如果您正在触摸DOM,您应该将jQuery内容包装在该块中; 这称为:文档加载的.ready()事件 。

你有没有尝试过:

 if($condition){ ?>  ?>  

可能问题是你没有等待加载DOM,请尝试:

 if($condition){ ?>  ?>  

但请注意这与php无关。