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

时间:2016-01-12 22:41:32

标签: javascript php wordpress

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,报告未找到错误。

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

PS:我正在安装SyntaxHighlighter,方法是在/body footer.php之前放置以下代码:

<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 个答案:

答案 0 :(得分: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' );

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

答案 1 :(得分:2)

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

在你的情况下将是:

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