wp_localize_script用于插入图像 [英] wp_localize_script for inserting an image
问题描述
我在wp_localize_script上遇到了一些麻烦.已经有很多关于此的问题,但是我不知道如何在特定情况下实现它们.我制作了一个jQuery文件,其中每个div之后都包含一个带有特定类的图像.jQuery本身很好,因为我可以使用段落标签更改image标签,然后将其显示在我的浏览器中.这是我在functions.php中拥有的
I'm having some trouble with wp_localize_script . There's plenty of questions about this already but I don't know how to implement them to this specific case. I made a jQuery file that includes an image after every div with a specific class. The jQuery itself is fine as I can change the image tag with a paragraph tag and then it shows up in my browser. Here's what I have in functions.php
function wpa_scripts() {
wp_enqueue_script(
'divider',
get_template_directory_uri() . '/js/divider.js',
array('jquery'),
null,
true
);
$script_data = array(
'image_path' => get_template_directory_uri() . '/images/'
);
wp_localize_script(
'divider',
'divider_data',
$script_data
); } add_action( 'wp_enqueue_scripts', 'wpa_scripts' );
这就是我的.js中的内容
And here's what I have in my .js
jQuery(document).ready(function($){
$('.contentpage').after('<img src=" '$script_data' + divider_placeholder.png">'); });
我可以告诉我我做错了什么吗?预先感谢.
Can I anyone tell me what I did wrong? Thanks in advance.
亲切的问候,斯蒂夫
推荐答案
您需要在jQuery函数中使用'divider_data.image_path'
而不是 $ script_data
:
You need to have 'divider_data.image_path'
instead of $script_data
in your jQuery function:
jQuery(document).ready(function($){
$('.contentpage').after('<img src="' + divider_data.image_path + 'divider_placeholder.png">');
});
参考: https://codex.wordpress.org/Function_Reference/wp_localize_script
这篇关于wp_localize_script用于插入图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!