【发布时间】: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>
这些是我浏览过但无法解决的一些资源:
- Set iframe url based on dynamic Url
- Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?
非常感谢!
【问题讨论】:
-
点击的时候一定要获取url,创建元素的时候不能插入正确的url吗?
-
@adeneo 为什么我们只做
document.createElement?我们可以html.createElement吗?? -
@Mahi 没有全局变量
html。document是包含代表整个 DOM 的对象的变量。
标签: javascript html