Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

javascript - WordPress path url in js script file

I added custom script:

wp_enqueue_script('functions', get_bloginfo('template_url') . '/js/functions.js', 'search', null, false);

It works great, except in the functions.js I have:

Reset.style.background = "url('../images/searchfield_clear.png') no-repeat top left";

This used to work before, until I changed to pretty permalinks and .htaccess

The folder hierarchy is like:

themename/js themename/images (the images and js folder are in themename folder)

I tried ../images - ./image - /images

Normally it should go back 1 level wherever the js file is located....

I don't want to use full path.

Is there another way that WordPress can recognize in the javascript file to have the correct path?

Currently I am just confused what I am doing wrong.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to the Wordpress documentation, you should use wp_localize_script() in your functions.php file. This will create a Javascript Object in the header, which will be available to your scripts at runtime.

See Codex

Example:

<?php wp_localize_script('mylib', 'WPURLS', array( 'siteurl' => get_option('siteurl') )); ?>

To access this variable within in Javascript, you would simply do:

<script type="text/javascript">
    var url = WPURLS.siteurl;
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...