[英]How do I refer to the root Wordpress directory INSIDE a Javascript file
I've got a javascript file and somewhere within the code I have this line: 我有一个javascript文件,并且在代码中的某处有这一行:
$(".section-divider.ornament").append('<img src="wp-content/themes/blackandwhite/img/divider-glyph.png" alt="" />');
I know it's not best practice to hard code in the directory like that, but I don't know how else to do it since: a) as far as I know, PHP doesn't work within JS files. 我知道在这样的目录中进行硬编码不是最佳实践,但是由于以下原因我不知道该怎么做:a)据我所知,PHP在JS文件中不起作用。 b) leaving it as "img/divider-glyph.png" (I've tried both with and without a leading '/') doesn't work either b)将其保留为“ img / divider-glyph.png”(无论是否使用前导“ /”,我都尝试过)也不起作用
I don't really like Wordpress so I keep my distance but I believe you can use this function to get the Wordpress base installation directory: 我不太喜欢Wordpress,所以我保持距离,但我相信您可以使用此功能来获取Wordpress基本安装目录:
<?php
get_bloginfo('wpurl');
?>
You can use that to add this information to the DOM, for instance the <body>
tag: 您可以使用它来将此信息添加到DOM中,例如<body>
标签:
<body data-base-dir="<?php echo get_bloginfo('wpurl'); ?>">
Then your JS could read this information: 然后您的JS可以读取以下信息:
var baseDir = $("body").data("data-base-dir");
Note than jQuery's .data()
method will only cache data-*
attributes that exist when jQuery loads, so updating an attribute or adding it after jQuery loads will require using .attr("data-*")
. 请注意,jQuery的.data()
方法将仅缓存jQuery加载时存在的data-*
属性,因此在jQuery加载后更新或添加属性将需要使用.attr("data-*")
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.