首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >找不到来自AssetBundle的JS文件(404错误)- Yii2

找不到来自AssetBundle的JS文件(404错误)- Yii2
EN

Stack Overflow用户
提问于 2016-09-14 12:48:52
回答 2查看 1K关注 0票数 0

我创建了yii 1应用程序,并使用以下脚本在视图文件中导航:

代码语言:javascript
复制
$(function() {
    $('a[href*="#"]:not([href="#"])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
            if (target.length) {
                $('html, body').animate({
                    scrollTop: target.offset().top
                }, 1000);
                return false;
            }
        }
    });
});

但是,当我创建yii2应用程序并粘贴此代码时,它无法工作。然后,我创建了新的menu_navigate.js js文件并粘贴了如下代码

代码语言:javascript
复制
$(function() {
        $('a[href*="#"]:not([href="#"])').click(function() {
            if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
                if (target.length) {
                    $('html, body').animate({
                        scrollTop: target.offset().top
                    }, 1000);
                    return false;
                }
            }
        });
    });

我使用以下代码在ThemeAsset中注册了此代码:

代码语言:javascript
复制
 public $js = [
 'Index/menu_navigate.js'
]

但是,这段代码对我没有帮助,也不能正常工作。我找不到任何错误。在控制台屏幕上显示以下错误消息

GET http://all/themes/CompanyProfile/Index/menu_navigate.js(未找到)

EN

回答 2

Stack Overflow用户

发布于 2016-09-14 12:53:41

使用“/Index/menu_Navigate.js”,这将帮助您获得正确的路径。

票数 0
EN

Stack Overflow用户

发布于 2016-09-14 13:40:02

如果此文件位于web可访问目录之外,则需要在资源包中设置正确的sourcePath

代码语言:javascript
复制
<?php

namespace app\assets;

use yii\web\AssetBundle;

class MenuNavigationAsset extends AssetBundle 
{
    public $sourcePath = '@bower/font-awesome'; // Replace with folder where "Index" folder is located. Path should be absolute, you can use aliases here.
    public $js = [ 
        'Index/menu_navigate.js', 
    ];    
}

然后,它将被复制到web可访问目录,并从那里加载。您可以通过官方文档来定义别名here。它可以防止你硬编码绝对路径。

否则(如果文件位于web可访问的目录中),请设置basePathbaseUrl属性:

代码语言:javascript
复制
<?php

namespace app\assets;

use yii\web\AssetBundle;

class MenuNavigationAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $js = [
        'Index/menu_navigation.js',
    ];   
}

准确检查浏览器尝试加载此js文件的路径,如果路径正确,则确保该文件存在;否则,请确保资源束中的路径正确。

还要检查path是否有拼写错误。

有关使用资产的官方文档,请参阅here

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39482660

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档