未定义的变量:我脚本中的窗口?

时间:2014-07-24 19:50:49

标签: javascript php yii

我有这个错误:

  

PHP注意 - yii \ base \ ErrorException

     

未定义的变量:窗口

     

函数inViewport($ el){

我的部分代码:

<?php
$lazyload = <<< JS
$(function() {
  var $window = $(window),
      images = [],
      imagesToBeLoaded = 0,
      i,
      src;

  function throttle(func, wait) {
    var timeout;
    return function() {
      var context = this, args = arguments;
      if(!timeout) {
        timeout = setTimeout(function() {
          timeout = null;
        }, wait);
        func.apply(context, args);
      }
    };
  }

  function inViewport($el) {
    var top = $window.scrollTop(),
        left = $window.scrollLeft(),
        bottom = top + $window.height(),
        right = left + $window.width(),
        offset = $el.offset(),
        thisTop = offset.top,
        thisLeft = offset.left,
        thisBottom = thisTop + $el.outerHeight(),
        thisRight = thisLeft + $el.outerWidth();

                      ...

JS;
$this->registerJs($lazyload, View::POS_READY);
?>

为什么会出现这个错误? 在codepen中,所有工作正常Codepen

1 个答案:

答案 0 :(得分:4)

引用heredoc的名称以防止PHP将$window解释为变量:

<?php
$lazyload = <<< 'JS'
...
JS;

(见http://php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc