我正在尝试建立一个href URL链接,其中包含一些javascript变量和用于交易电子邮件的静态文本。但是,我无法获取链接或显示的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>
答案 0 :(得分:3)
您遇到了问题
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>
答案 1 :(得分:2)
最好的解决方案是使用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>
答案 2 :(得分:0)
您可以尝试以下方法:
<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好方法。