2016-09-14 226 views
0

我创建YII 1个应用,并且为了在视图文件中导航使用以下脚本:JS文件未找到(404错误) - Yii2

$(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(未找到)

+0

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

回答

0

使用“/Index/menu_navigate.js”,这将有助于你得到正确的路径。

+0

这里,其他js文件正常工作,这些工作js文件正在使用'index/___。js'路径,它们正常工作。但是,我创建的js文件不起作用 – phpdev

+0

您是否在“ThemeAsset”中包含了jquery.min.js。因为你写的代码使用jquery,所以只有在DOM被创建后才能使用。如果它仍然没有解决,试图直接使用registerScript函数。请参阅:http://stackoverflow.com/questions/28781463/yii2-include-js-script-only-for-specific-view – Mahi

+0

不需要在资产包中使用js和css文件名引导斜杠。 – arogachev

0

如果该文件是网络访问的目录外,你需要设置正确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', 
    ];  
} 

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

否则(如果文件在网络访问的目录),设置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文件,确保文件存在那里,如果路径是正确的,否则资产包中的路径是正确的。

另请检查错误路径。

官方文档使用资产可用here