首页 文章

如何创建相对于当前文件目录的JavaScript文件路径?

提问于
浏览
0

JavaScript文件路径与显示的页面相关 . 如何创建相对于当前文件目录的JavaScript文件路径?

例如,我将 sh/shThemeDefault.css 文件包含在 footer.php (在同一目录下: wordpress/wp-content/themes/ )中:

<script src="sh/shCore.js" type="text/javascript"></script>

在访问帖子时(比如 http://example.com/post-A ),

sh/shCore.js 将扩展为 http://example.com/post-A/sh/shCore.js ,报告 not found 错误 .

正确的绝对路径是 http://example.com/wordpress/wp-content/themes/sh/shCore.js .


PS:我通过在 footer.php 之前的 /body 之前放置以下代码来安装SyntaxHighlighter

<link href="./sh/shCore.css" rel="stylesheet" type="text/css" />
<link href="./sh/shThemeDefault.css" rel="stylesheet" type="text/css" />

<script src="./sh/shCore.js" type="text/javascript"></script>
<script src="./sh/shAutoloader.js" type="text/javascript"></script>


<script type="text/javascript">
SyntaxHighlighter.autoloader(
    ['python', 'py', 'sh/shBrushPython.js'],
    ['java', 'sh/shBrushJava.js'],
    ['bash','shell','sh/shBrushBash.js'],
    ['css','sh/shBrushCss.js'],
    ['sql','sh/shBrushSql.js'],
    ['latex', 'tex','sh/shBrushLatex.js.js'],
    ['plain', 'text','sh/shBrushPlain.js'],
    ['php','sh/shBrushPhp.js'],
    ['js','jscript','javascript','sh/shBrushJScript.js'],
    ['xml', 'xhtml', 'xslt', 'html', 'xhtml','sh/shBrushXml.js']
);
SyntaxHighlighter.all();
</script>

2 回答

  • 2

    您不应该直接在WordPress模板中包含CSS和JS文件 . 相反,你应该通过wp_enqueue_style()正确地将它们排入(在functions.php中):

    /**
     * Proper way to enqueue scripts and styles
     */
    function theme_name_scripts() {
        wp_enqueue_style( 'style-name', get_stylesheet_directory_uri() . '/shThemeDefault.css' );
        wp_enqueue_script( 'script-name', get_stylesheet_directory_uri() . '/js/example.js', array(), '1.0.0', true );
    }
    add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );
    

    这将完全消除您遇到的问题 .

  • 2

    在Wordpress中,您可以使用以下代码获取模板目录: <?php echo get_template_directory_uri(); ?>

    在你的情况下将是这样的:

    <link href="<?php echo get_template_directory_uri(); ?>/sh/shThemeDefault.css" rel="stylesheet" type="text/css" />
    

相关问题