【问题标题】:How to insert a dynamic URL into an href如何将动态 URL 插入到 href
【发布时间】:2016-11-18 22:56:43
【问题描述】:

我希望生成一个动态 URL 并将其插入到 HTML 标记中,然后使用 .innerHTML 属性将其添加到页面中。

for (n = 0; n <= allImages.length - 1; n++) { // This cycles through all the images on the page.

  function getUrl() {

    var srcUrl = document.images[n].src;
    return srcUrl; // Then I get the src URL for each image and return it.

  }

  var newP = document.createElement('p');
  newP.innerHTML = document.images[n].naturalWidth + " x " + document.images[n].naturalHeight + " " + '<a href= \'javascript:window.location=getUrl();\'>LINK</a> '; // Run the 'getURL' function so the word LINK directs the viewer to the specific image URL. 

  imgUrlDiv.appendChild(newP); // Append the code each time to a new <p>
}

我遇到的问题是,由于 getURL 函数是作为“href”的值添加的,所以它必须用引号引起来,所以它变成了一个字符串(我的猜测),所以它被渲染为是和不提取正确的图像 URL。

有没有办法将 getURL 函数插入到 href 的值中,并让它呈现页面上每个图像的链接?

<a href= \'javascript:window.location=getUrl();\'>LINK</a>

这些是我浏览过但无法解决的一些资源:

非常感谢!

【问题讨论】:

  • 点击的时候一定要获取url,创建元素的时候不能插入正确的url吗?
  • @adeneo 为什么我们只做document.createElement ?我们可以html.createElement 吗??
  • @Mahi 没有全局变量htmldocument 是包含代表整个 DOM 的对象的变量。

标签: javascript html


【解决方案1】:

创建元素时添加图片源作为href

for (var n = 0; n < allImages.length; n++) {
    var img  = document.images[n];
    var newP = document.createElement('p');
    var newA = document.createElement('a');
    var newT = document.createTextNode(img.naturalWidth + " x " + img.naturalHeight + " ");

    newA.href = img.src;
    newA.textContent = 'LINK';

    newP.appendChild(newT);
    newP.appendChild(newA);

    imgUrlDiv.appendChild(newP);
}

【讨论】:

  • 谢谢@adeneo!我真的很喜欢这种方法并且学到了很多东西!谢谢!
【解决方案2】:

如果你使用:

newP.innerHTML = document.images[n].naturalWidth + " x " + document.images[n].naturalHeight + " " + "<a href= '"+getUrl()+"'>LINK</a> ";

您可以调用“getURL”函数,以便在新段落中打印出图像宽度和高度的字符串表示形式,并且单词 LINK 将查看者引导至特定的图像 URL。

【讨论】:

  • 非常感谢巴克!我不知道“+”会起作用:)
猜你喜欢
  • 2012-09-09
  • 1970-01-01
  • 2012-02-06
  • 2019-12-03
  • 2015-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多