【问题标题】:Add jquery in Yii 2.0在 Yii 2.0 中添加 jquery
【发布时间】:2015-11-17 15:54:25
【问题描述】:

如何在 Yii 2.0 中添加 jQuery 到我的页面?

在 Yii 1.x 中你可以使用:

Yii::app()->clientScript->registerCoreScript('jquery');

我已经尝试用自己的 View 类覆盖并尝试在那里注册 jQuery,但它没有显示在我的 html 页面中:

namespace frontend\components;

/**
 * This is the base view object, it extends the yii\web\View so you can add custom view stuff here.
 */

class BaseView extends \yii\web\View {


    public function init()
    {

        parent::init();
        \yii\web\JqueryAsset::register($this);

    }


}

【问题讨论】:

    标签: php jquery yii2


    【解决方案1】:

    我想你使用了正确的注册 jquery 的方法。但是如果你注册了至少一个位置 = POS_READY 的 js,例如(在视图内部),基础 Yii 2.0 视图类也会自动注册 jquery:

    $this->registerJs($js, \yii\base\View::POS_READY);
    

    或在任何控制器或小部件内:

    $this->getView()->registerJs($js, \yii\base\View::POS_READY);
    

    所以如果你使用任何 javascript 代码或文件(你使用它,因为你需要 jquery)你可以完全摆脱那个 JqueryAsset。

    【讨论】:

    • 好的,谢谢!它以这种方式工作,请参阅我的答案 ;-) 我忘记将视图方法放在我的视图中。
    • 应该是\yii\web\View::POS_READY。 (可能是他们在 alpha 更新中更改了它?)
    【解决方案2】:

    解决了!我忘了把视图方法放在我的视图文件中:($this->beginBody() 等等)

    【讨论】:

    • 这是在布局 main.php 文件中吗?
    【解决方案3】:

    如果你想包含一个来自控制器的 js 文件,你也可以使用这个

     public function actionIndex() {
        $this->getView()->registerJsFile('js/fileinput.js');
    
                return $this->render('index', [
                            'model' => $model,
                ]);
    }
    

    如果您想了解更多详情,请查看此链接

    http://www.yiiframework.com/doc-2.0/guide-output-client-scripts.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-30
      • 1970-01-01
      • 1970-01-01
      • 2015-03-03
      相关资源
      最近更新 更多