Yii2的View中JS代码添加

直接写

<script>
$(function(){
  alert("aaa");
});
<script>

会提示出错

是因为view中添加js代码的前面没有引用juqery.js,默认全局的jquery则是在文件尾添加

解决方法

(1)

在代码前加引入js文件(两种方式)

  1. <?=Html::jsFile('@web/js/jquery.js')?>
  2. <?php $this->registerJsFile('@web/js/jquery.js');?>

(2)

想用用全局的js文件,这样写

<?php
$js = <<<JS
$(function(){
  alert("aaa");
});
JS;
$this->registerJs($js);
?>

 

posted @ 2015-08-27 09:06  慕尘  阅读(1288)  评论(0编辑  收藏  举报