作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已经阅读了文档,但不知道该怎么做,例如我在 View 文件夹 medicine-issue-entry< 中的文件
像:index.php
中有一个小脚本
<?php
$js = 'function refresh() {
$.pjax.reload({container:"#medicine_request_entry"});
setTimeout(refresh, 60000); // restart the function every 5 seconds
}
refresh();';
$this->registerJs($js, $this::POS_READY);
?>
我可以在哪里将这段代码放在一个单独的文件中,以及如何将它包含在相关文件中。一个详细的过程将不胜感激。谢谢。
好的,我正在使用基本模板。在 AppAsset.php
中,我包含了类似内容
public $js = [
'js/autorefresh.js'
];
并在 web 文件夹
中创建了一个文件夹 js
并使用以下代码创建了一个新文件 autorefresh.js:
function refresh() {
$.pjax.reload({container:"#medicine_request_entry"});
setTimeout(refresh, 60000); // restart the function every 5 seconds
}
refresh();
在我的 index.php
中添加了这一行
namespace app\assets;
use app\assets\AppAsset;
AppAsset::register($this);
但是还是不行,我是不是还漏掉了什么?当我使用 registerJs
将代码包含在文件中时,它工作正常。
注意:查看页面源文件时,文件已正确发布并单击链接显示脚本,但代码无法正常工作。
最佳答案
使用 Yii2 的基本模板
将您的autorefresh.js
脚本添加到/web/js/
目录
function refresh() {
$.pjax.reload({container:"#medicine_request_entry"});
setTimeout(refresh, 60000); // restart the function every 5 seconds
}
refresh();
将您的脚本添加到位于 /assets/AppAsset.php
的 AppAsset 类内的 $js
数组中
<?php
namespace app\assets;
use yii\web\AssetBundle;
class AppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'css/site.css',
];
public $js = [
'js/autorefresh.js',
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
}
确保您的 AssetBundle 已注册。
use app\assets\AppAsset;
AppAsset::register($this);
或
\app\assets\AppAsset::register($this);
NOTE: Your don't set the namespace of the index.php file.
关于Yii2:如何为脚本使用 Asset Bundle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28075019/
我是一名优秀的程序员,十分优秀!