Home  >  Article  >  PHP Framework  >  How to add js code to View in yii2

How to add js code to View in yii2

王林
王林Original
2020-02-19 15:50:522868browse

How to add js code to View in yii2

如果直接按如下方式添加,如:

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

会提示出错。

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

(相关教程推荐:yii框架

解决方法:

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

<?=Html::jsFile(&#39;@web/js/jquery.js&#39;)?>
<?php $this->registerJsFile(&#39;@web/js/jquery.js&#39;);?>

2、使用全局的js文件,例如:

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

更多编程相关内容,请关注php中文网编程入门栏目!

The above is the detailed content of How to add js code to View in yii2. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn