简体   繁体   English

我如何在Javascript文件中引用Wordpress根目录

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

相关问题 如何在 NodeJS 中引用 Linux Azure VM 上的文件夹/文件目录? - How do I refer to a folder/file directory on Linux Azure VM in NodeJS? Wordpress-如何将主题目录放在js文件中? - Wordpress - How do I take the theme directory in a js file? 如何从节点包库中的根项目目录中获取某些内容? - How do I require something in root project directory from inside node package library? 如何使 HTML 按钮引用外部 javascript 文件中的操作? - how do I make the HTML button refer to an action in an external javascript file? 如何在 querySelectorAll 的过滤器函数中引用“this”? - How do I refer to “this” inside filter function of querySelectorAll? WordPress:我该如何正确排入此javascript文件? - Wordpress: How do I correctly enqueue this javascript file? 我如何在javascript中引用子函数中的父对象值 - how do i refer to the parent object value in child function in javascript 如何在javascript侦听器中引用复合组件? - How do I refer to composite component in javascript listener? 如何在Javascript中引用ASP.NET控件? - How do I refer to ASP.NET Controls in Javascript? 在 javascript 如何引用 this.form.checkbox[5].checked? - In javascript how do I refer to this.form.checkbox[5].checked?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM