[英]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.