将 javascript 变量插入交易电子邮件中的 href link

Insert javascript variables into a href link within a transactional email

我正在尝试构建一个 href url link,其中包含一些 javascript 变量和交易电子邮件的静态文本。但是,我无法将 link 或显示的 URL 显示为完整构建的 URL。

我试过用单引号和其他一些变体将它们括起来,但是 URL 和显示的 URL 将无法正确显示。谁能帮忙解决这个问题?

var folder = "orders";
var orderNumber = "589";
var refNum = "Mon";
var job = "image";

HTML

<p style="margin: 0;">If that button will not work, copy and paste the following link in your browser:</p>
<p style="margin: 0;"><a href='"https://example.com/ + folder + "/" + orderNumber + "-" + refNum + "-" + job + ".jpg"' target="_blank">'"https://example.com/" + folder + "/" + orderNumber + "-" + refNum + "-" + job + ".jpg"'</a></p>

你的拼接有问题

href='"https://example.com/ + folder +
                           |___________  Here you should have `"`

您可以直接使用 Template literals

var folder = "orders";
var orderNumber = "589";
var refNum = "Mon";
var job = "image";

let link = `<p style="margin: 0;"><a href='"https://example.com/${folder}/${orderNumber}-${refNum}-${job}.jpg' target="_blank">https://example.com/${folder}/${orderNumber}-${refNum}-${job}.jpg</a></p>`

document.querySelector('#link').innerHTML = link

console.log(link)
<div id='link'></div>

最好的解决方案是使用 template literal 创建端点,然后使用另一个创建 HTML。那么你就不用担心所有的引号和它们的顺序了:

var folder = "orders";
var orderNumber = "589";
var refNum = "Mon";
var job = "image";

const endpoint = `https://example.com/${folder}/${orderNumber}-${refNum}-${job}.jpg`;
const href = `<a href="${endpoint}" target="_blank">${endpoint}</a>`;

document.querySelector('.link').insertAdjacentHTML('beforeend', href);
<p style="margin: 0;">If that button will not work, copy and paste the following link in your browser:</p>
<p class="link" style="margin: 0;"></p>

你可以试试这个:

<p style="margin: 0;">
   <a id="myLink" href='' target="_blank">""</a>
</p>

 <script type="text/javascript">
     var folder = "orders";
     var orderNumber = "589";
     var refNum = "Mon";
     var job = "image";

     var myLink = document.getElementById("myLink");
     myLink.href = "https://example.com/" + folder 
              + "/" + orderNumber + "-" + refNum + "-" + job + ".jpg";

     myLink.innerHTML = myLink.href;
 <script>

如果您希望它简洁且通用,那么模板化是您的不二之选。否则你可以尝试使用旧的 JS 方法。