1.直接方式
1.1简述
使用 yii\web\View 对象时,可以动态注册前端脚本。 这里有两个专门的方法:
- registerJs() 用于内联脚本。
- registerJsFile() 用于注册引入外部脚本文件。
- registerCss() 用于内联脚本。
- registerCssFile() 用于注册引入外部脚本文件。
1.2例子
$this->registerJs(
"$('#myButton').on('click', function() { alert('Button clicked!'); });",
View::POS_READY,
'my-button-handler'
);
$this->registerJsFile(
'@web/js/main.js',
['depends' => [\yii\web\JqueryAsset::className()]]
);
$this->registerCss("body { background: #f00; }");
$this->registerCssFile("@web/css/themes/black-and-white.css", [
'depends' => [\yii\bootstrap\BootstrapAsset::className()],
'media' => 'print',
], 'css-print-theme');
第一个参数指明被注册的 CSS 文件。
第二个参数指明 <link> 标签的 HTML 属性,选项 depends 是专门处理 指明 CSS
文件依赖于哪个资源包。在
这种情况下,依赖资源包就是 yii\bootstrap\BootstrapAsset。这意味着 CSS 文件将
被添加在 yii\bootstrap\BootstrapAsset 之后。
最后一个参数指明一个 ID 来标识这个 CSS 文件。 如果参数未提供,则将使用 CSS 文件的 URL。