【发布时间】:2021-02-24 11:45:16
【问题描述】:
我想制作一个更改图像的 JavaSript 代码。我的意思是有两个图像和一个按钮。图片路径为/assets/images/svg/outline-img1.svg 和/assets/images/svg/outline-img.svg。还有一个按钮,它应该更改所有具有相同 id (id="changeimg") 的图像路径。
我想当您单击按钮时,它应该更改包含changeid 的图像。这很简单,但我真正想要的只是改变路径的一部分。我的意思是我想将路径从/assets/images/svg/outline-img1.svg 更改为/assets/images/svg/filled-img.svg。但是是否可以更改所有包含changeimg id 的图像路径?
有没有代码sn-p 比如这个?
document.querySelector('.btn').addEventListener("click",
function () {
$('#changeimg').attr('src', '/assets/images/svg/filled-'+imgname+'.svg');
/*
imgname should be the name of the image between the '/assets/images/svg/outline' and the '-.svg'. (In this example imgname = shape and imgname = shape2)
So the it should change the elements that contains the '#changeimg' id from '/assets/images/svg/outline-shape.svg' to '/assets/images/svg/filled-shape.svg'
And all the images with the changeimg id should be changed.
*/
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="/assets/images/svg/outline-shape.svg" id="changeimg">
<img src="/assets/images/svg/outline-shape2.svg" id="changeimg">
<button class="btn">Change</button>
我知道这有点难以理解,如果你愿意,我可以重新定义我的问题。
【问题讨论】:
-
ID 应该是唯一的。
-
那我应该用类来做吗?
-
是的,很难理解为什么人们会多次使用同一个 id,尽管 docs says 认为 id 在文档中必须是唯一的。
-
请详细说明。
-
@Swati 所以我想制作一个按钮来更改所有具有相同类别的图像,但不是针对特定图像。图片的路径应该从
/assets/images/svg/outline-img.svg更改为/assets/images/svg/filled-img.svg,但只更改outline和filled字。现在清楚了吗?
标签: javascript html jquery css svg