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

How to add js code to View in yii2

王林
Release: 2020-02-19 15:50:52
Original
2930 people have browsed it

How to add js code to View in yii2

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

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

会提示出错。

因为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;);?>
Copy after login

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

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

更多编程相关内容,请关注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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template