2

如何在视图文件中由 Datepicker 小部件生成的 javascript 代码之后包含我的 .js 文件。

            echo DatePicker::widget([
                'name'  => 'datepicker--2',
                'id' => 'datepicker--2',
                'clientOptions' => [
                    'showOtherMonths' => true,
                    'maxDate' => '+ 0d',
                    'showOtherMonths' => true,
                    'selectOtherMonths' => true,
                ]
            ]);

我的资产包:

namespace app\assets;

use yii\web\AssetBundle;

class ChartsAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $js = [
        'js/charts.js',
        'js/charts-init.js',
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\jui\JuiAsset',
        'yii\web\JqueryAsset',
    ];
}

我在我的页面源上得到了什么:

...
<script src="/new/js/charts.js"></script>
<script src="/new/js/charts-init.js"></script>
<script type="text/javascript">jQuery(document).ready(function () {
$('#datepicker--2').datepicker($.extend({}, {"showOtherMonths":true,"maxDate":"+ 0d","selectOtherMonths":true,"dateFormat":"M d, yy"}));
});</script></body>
</html>
4

2 回答 2

4

使用 yii2,您可以选择在文档中定义客户端脚本的位置(HEAD、BEGIN 或 END)。这可以通过做这样的事情来实现

public $jsOptions = [
        'position' => \yii\web\View::POS_HEAD
 ];

或使用这个。

于 2015-01-23T01:55:23.503 回答
1

像这样创建BaseAssets

namespace app\assets;

class BaseAsset extends AssetBundle
{
    public $sourcePath = '@resources'; // @app/resources
    public $css = [];  
    public $js = [];    
    public $depends = [
        'yii\web\YiiAsset',
        'yii\jui\JuiAsset',
        'yii\web\JqueryAsset',
    ];         
    public $jsOptions = [ 'position' => \yii\web\View::POS_HEAD ];
}

你的Assets

namespace app\assets;

use yii\web\AssetBundle;

class ChartsAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $js = [
        'js/charts.js',
        'js/charts-init.js',
    ];
    public $depends = [
        'app\assets\BaseAssets',        
    ];
    public $jsOptions = [ 'position' => \yii\web\View::POS_END ];
}
于 2015-02-18T18:12:17.837 回答