YII2.0 错误 $ is not defined

BUG:$ is not defined 没有加载jquery成功

因为Yii2.0将JS代码默认加载页面加载后,最简单方法是在 assets\AppAsset.php 中加上

public $jsOptions = array(
    'position' => \yii\web\View::POS_HEAD
);

页面前加载

But in production you usually want the scripts to load last, and instead you let Yii2 handle your javascript:

$this->registerJs(
    '$("document").ready(function(){ alert("hi"); });'
);

Now Yii will handle this js and place it after anything important (like jQuery).

You'll however soon notice that IDE's are usually bad at handling this kind of language nesting (JavaScript inside PHP) so the syntax highlighting is likely to break. One way to solve it is to register your script in a separate file:

$this->registerJsFile( 'myScript.js' );

If you want even more control about which order to load your scripts, you can add dependencies as your second argument, and additional options as the third:

$this->registerJsFile( 
    'myScript.js', 
    ['\backend\assets\AppAsset'],  
    ['position' => '\yii\web\View::POS_END']
);

If you for some reason absolutely want the script to be rendered inline you can do:

$this->registerJs( $this->renderPartial('myScript.js') );

The recommended way to add your scripts is to use AssetBundles. Look in assets/AppAssets.php and add your js-file to the $js-array.

转载于:https://my.oschina.net/u/1015435/blog/800977

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值