我的 View 中有 ActiveForm,我使用 $this->addError
在模式内验证它。但是,当我使用事件表单加载页面时,我在调试控制台中看到:
TypeError: window.jQuery is not a function yii.js:520:1
ReferenceError: jQuery is not defined yii.validation.js:452:1
TypeError: $ is undefined yii.activeForm.js:14:5
jQuery.Deferred exception: jQuery(...).yiiActiveForm is not a function @http://localhost:8888/?XDEBUG_SESSION_START=14982:770:1
l@http://localhost:8888/plugins/jquery/jquery.min.js:2:29373
a/</c<@http://localhost:8888/plugins/jquery/jquery.min.js:2:29677
undefined
jquery.min.js:2:30920
TypeError: jQuery(...).yiiActiveForm is not a function
我查看页面源代码,发现js文件的加载顺序是错误的,在浏览器中是这样的:
</script><script src="/assets/d69283db/yii.js"></script>
<script src="/assets/d69283db/yii.validation.js"></script>
<script src="/assets/d69283db/yii.activeForm.js"></script>
<script src="/plugins/jquery/jquery.min.js"></script>
<script src="/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/plugins/iCheck/icheck.min.js"></script>
<script src="/dist/js/login.js"></script>
在我的资源文件中,设置是:
AppLoginAsset.php:
使用 yii\web\AssetBundle;
class AppLoginAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'/plugins/font-awesome/css/font-awesome.min.css',
'https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css',
'/dist/css/adminlte.min.css',
'/plugins/iCheck/square/blue.css',
'https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700'
];
public $js = [
'/plugins/jquery/jquery.min.js',
'/plugins/bootstrap/js/bootstrap.bundle.min.js',
'/plugins/iCheck/icheck.min.js',
'/dist/js/login.js'
];
public $depends = [
];
}
如何更改加载顺序,在实际 yii 资源之前加载 jquery?我尝试过这样修改:
public $js = [
// '/plugins/jquery/jquery.min.js', <-- commented this
// '/plugins/bootstrap/js/bootstrap.bundle.min.js', and this
'/plugins/iCheck/icheck.min.js',
'/dist/js/login.js'
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset'
];
但错误仍然是相同的,并且 jquery 和 boostrap 的资源由于某种原因没有添加,即使它们存在。
最佳答案
这个问题的主要问题是 jQuery 没有首先加载。
创建另一个严格加载 jQuery 的包,并将其传递到 AppLoginAsset
的 depends
属性中,这样,您就可以完全控制依赖项。
LE - 所以你改变了你的depends
,但它仍然不起作用..你是否在应用程序的引导过程中或主配置文件中取消设置(或清空它们)默认 bundle 中的任何内容?在我看来,您想要自定义 Bootstrap 和 jQuery,但您可能忘记了在“运行时”更改这些 bundle 。
此外,删除 assets
目录中的目录,以便 Yii2 重新组合它们。
关于jquery - Yii2 javascript 加载顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50711269/