[英]Problem in adding pictures in Javascript function in WordPress theme
我遇到了一个问题,无法以WordPress主题在javascript文件中显示图像,我尝试使用<?php echo esc_url(get_template_directory_uri());?>
但在JS文件中不起作用,
因此此行不起作用,因为它在JS文件中:
document.getElementById("women-eyes1").src="<?php echo
esc_url(get_template_directory_uri());?> images/ss1.png";
如何在js文件中定向图像?
您不能在js文件file.js
使用php函数。 您可以在PHP文件中使用内联脚本,如下所示:
// some php file
// output the script
?>
<script>
document.getElementById("women-eyes1").src="<?php echo
esc_url(get_template_directory_uri());?> images/ss1.png";
</script>
<?php // rest of your php
或者您可以使用wp_localize_script并传递如下值:
<?php
// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );
// Localize the script with new data
$translation_array = array(
'some_string' => __( 'Some string to translate', 'plugin-domain' ),
'a_value' => '10'
);
wp_localize_script( 'some_handle', 'object_name', $translation_array );
// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );
然后在您的js文件中使用变量:
<script>
// alerts 'Some string to translate'
alert( object_name.some_string);
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.