簡體   English   中英

未找到 AssetBundle 中的 JS 文件(404 錯誤)- Yii2

[英]JS file from AssetBundle not found (404 Error) - Yii2

我創建了 yii 1 應用程序並使用以下腳本在視圖文件中導航:

$(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 文件並粘貼了類似的代碼

$(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 中注冊了此代碼:

 public $js = [
 'Index/menu_navigate.js'
]

但是,這段代碼對我沒有幫助,而且它不起作用。 我無法找到任何錯誤。 在控制台屏幕中,它顯示以下錯誤消息
GET http://all/themes/CompanyProfile/Index/menu_navigate.js (未找到)

使用“ /Index/menu_navigate.js”,這將幫助您獲取正確的路徑。

如果此文件位於可通過Web訪問的目錄之外,則需要在資產捆綁包中設置正確的sourcePath

<?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可訪問目錄並從那里加載。 您可以在此處提交用於定義別名的官方文檔。 它可以防止您對絕對路徑進行硬編碼。

否則(如果文件位於Web可訪問目錄中),則設置basePathbaseUrl屬性:

<?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文件的路徑,並確保該文件存在(如果路徑正確),否則請確保資產捆綁包中的路徑正確。

還要檢查輸入錯誤的路徑。

有關使用資產的官方文檔可在此處獲得

您應該將文件 css 或 js 放入文件夾 web 的 js、css 中。 然后更改文件->

class BackendAsset extends AssetBundle
{
    public $basePath='@webroot';
    public $baseUrl='@web';
    public $css=[
        'css/style.css'
    ];
    ...... `code of you`
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM