自动为图片填充HTML文件路径的Javascript

时间:2018-12-03 17:36:53

标签: javascript html image innerhtml pathname

我正在尝试使用window.location.pathname并注入innerHTML来生成图像的文件路径,所以我要做的就是在html主体的div中键入fileName.png并让javascript生成文件后面的路径,以便它在渲染的网站中显示图像。这适用于未与工作文件存储在同一文件夹中的图像。 我取得了轻微的成功,但每页只能显示一张图像,效果不是很好。

我已经将此代码用于每页一张图像:

<div class="picName">pic.png</div><div id=<"shortcut"></div>`

<script>
  var relativePath = window.location.pathname;
  var picName = document.getElementById('matts-shortcut').previousElementSibling.innerHTML;
  document.getElementById("matts-shortcut").innerHTML =
    '<src=\'/images' + relativePath + '/' + picName + '\'>';

</script>

2 个答案:

答案 0 :(得分:1)

以下解决方案使用.querySelectorAll()从Div中提取图像名称,该图像返回DOM NodeList。 NodeList之所以有用,是因为它具有forEach()方法,该方法可用于遍历列表的每个项目。使用其textContent属性作为图像名称来遍历每个列表项。然后,您需要为每个图像创建一个新的图像元素。为此,您可以执行类似的操作。

let relativePath = "https://dummyimage.com"; // replace the url with path name (maybe window.location.path)
// create a reference to the input list
// querySelectorAll return a NodeList
let inputNameList = document.querySelectorAll('.image-name');
// Loop through each image name and append it to the DOM
// the inputNameList (NodeList) has a "forEach" method for doing this
inputNameList.forEach((image) => {
  let picName = image.textContent;
  // Create a new image element
  let imgEl = document.createElement('img');
  // Set the src attribute of the image element to the constructed URL
  // the name of the picture will be the div text content
  // This is done with a template literal that you can learn about here:
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
  imgEl.src = `${relativePath}/${image.textContent}`;
  // Now we have a real image element, but we need to place it into the DOM so it shows up
  // Clear the image name
  image.textContent = "";
  // Place the image in the Div
  image.appendChild(imgEl);
});
<div class="image-name">300.png</div>
<div class="image-name">200.png</div>
<div class="image-name">100.png</div>
<div class="image-name">400.png</div>

编辑:针对Ismael的批评,我对代码进行了少量编辑,并对每一行都进行了注释,以便您可以从此答案中学习。代码中引用了两个超链接,以帮助您考虑以现代方式进行编码,因此您可以更轻松地解释阅读的现代代码。

关于:

修改2: 经过进一步澄清,对答案进行了修改,以从DOM中已经存在的Div元素中提取图像文件名。

答案 1 :(得分:0)

让ID等于您元素的ID

致电: document.getElementById(ID).src =“ image_src” 当您想要更改图像时,例如onclick动作或作为功能的一部分。