简体   繁体   English

javascript / jquery-用全局变量替换文本

[英]javascript/jquery - replace text with global variable

I've created a documentation of an api which contains api endpoints, curl call syntax. 我创建了一个API文档,其中包含api端点,curl调用语法。 It's a pure html document with pre and blockquote tags for code blocks. 这是一个纯html文档,带有用于代码块的preblockquote标签。 Currently the documnetation is for version 1.0. 目前,文档记录适用于1.0版。 So the api calls are as below: 因此,api调用如下所示:

https://api.xxx.com/v1

Now we are going to release next version. 现在我们将发布下一个版本。 And the url will be changed to https://api.xxx.com/v1.1 and so on. 网址将更改为https://api.xxx.com/v1.1 ,依此类推。 It is very tidious to change all urls manually in the documentation. 手动更改文档中的所有URL非常麻烦。 So I created a global variable as below and thought that only one change will reflect to all urls in documentation. 因此,我如下创建了一个全局变量,并认为只有一个更改将反映到文档中的所有url。

window._respapiurl = "https://api.xxx.com/v1";

My way is to change version number in a variable so it will work for all the urls. 我的方法是更改​​变量中的版本号,以便它适用于所有网址。

And tried to replace it in a pre tag as <pre class="highlight plaintext"><script>window._respapiurl</script></pre> . 并尝试将其替换为pre标签中的<pre class="highlight plaintext"><script>window._respapiurl</script></pre> But it didn't work due to the behaviour of pre tag. 但是由于pre标签的行为,它无法正常工作。

How do replace all the urls in documentation with global variable ??? 如何用全局变量替换文档中的所有URL ???

1) You can use some setting file in PHP and set version url there, so you just change version variable. 1)您可以在PHP中使用一些设置文件并在那里设置版本url,因此只需更改版本变量即可。

$appVersion = '1.1';
echo "https://api.xxx.com/v{$appVersion}";

2) Use urls with placeholder, so you can loop and replace it: 2)使用带占位符的url,因此您可以循环并替换它:

$(document).ready(function() {
  var appVersion = '1.1';

  $.each($("span.versionLink"), function() {
    var newText = $(this).text().replace("{version}", appVersion);
    $(this).text(newText);
  });

  $.each($("a.versionLink"), function() {
    var newLink = $(this).attr("href").replace("{version}", appVersion);
    $(this).attr("href", newLink)
  });
});

<pre>
  <span class="versionLink">https://app/v{version}</span>
  <a href="https://app/v{version}" class="versionLink">Link to another documentation</a>
</pre>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM