javascript - undefined variable : window in my script?

标签 javascript php yii

我有这个错误:

PHP Notice – yii\base\ErrorException

Undefined variable: window

function 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

最佳答案

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

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

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

关于javascript - undefined variable : window in my script?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24942748/

相关文章:

javascript - 是否可以同时更改克隆和原始元素? -jQuery

php - mysql正则表达式匹配带点和不带点的字符串

php - [PHP 警告 : mail(): "sendmail_from" not set in php. ini 或自定义 "From:" header 丢失

yii : how to config SEO friendly url at Yii?

php - 过滤 GridView 中不在表 yii2 中的自定义列

javascript - 在 reactjs 中渲染和类中的函数

javascript - MVC Model 2 Web App 在性能上能否比 Model1 Web App 更快?

php - 如何在 Yii 中转储变量以进行调试?

javascript - 使用javascript在iframe中查看多个url

php - php 中的背景 css