使用 javascript/jquery,更新一组图像的 src 的最佳方法是什么?
Using javascript/jquery, what is the best way to update the src of a set images?
我的页面上有一堆图片,如下所示:
<img src="/Content/Images/Icons/Theme1/title.png" class="slideExampleImage">
<img src="/Content/Images/Icons/Theme1/test.png" class="slideExampleImage">
<img src="/Content/Images/Icons/Theme1/bill.png" class="slideExampleImage">
如您所见,所有图像都有 class="slideExampleImage",并且所有文件都在当前主题名称的目录中。
我有一个用于不同主题的文件夹,我想让我的用户更改主题,所以我有每个主题名称的单选按钮,所以你可以假设我可以将 selected 主题名称放入局部变量
var theme = GetThemeNameFromRadioButton();
我正在尝试找出允许用户 select 不同主题(比方说 "Theme2")的最佳方法,这将导致图像看起来像这样
我有不同的主题,我想要一种更改主题的方法
<img src="/Content/Images/Icons/Theme2/title.png" class="slideExampleImage">
<img src="/Content/Images/Icons/Theme2/test.png" class="slideExampleImage">
<img src="/Content/Images/Icons/Theme2/bill.png" class="slideExampleImage">
所以以某种方式进入并更新 src 并将图像下的一个子文件夹(在本例中为 Theme1)替换为选择的新主题(在本例中为 Theme2)
使用 jquery / javascript 实现该目标的方法是什么?请注意,我无法控制主题名称,因为用户可以将主题与任何名称相同
function changeTheme(newTheme) {
// change the "src" attribute
$(".slideExampleImage").attr("src", function(_, oldSrc) {
// split the path
var parts = oldSrc.split(/\//);
// replace the "theme" part of the path with the new one
parts.splice(parts.length - 2, 1, newTheme);
// return/set the new path
return parts.join("/");
});
}
我的页面上有一堆图片,如下所示:
<img src="/Content/Images/Icons/Theme1/title.png" class="slideExampleImage">
<img src="/Content/Images/Icons/Theme1/test.png" class="slideExampleImage">
<img src="/Content/Images/Icons/Theme1/bill.png" class="slideExampleImage">
如您所见,所有图像都有 class="slideExampleImage",并且所有文件都在当前主题名称的目录中。
我有一个用于不同主题的文件夹,我想让我的用户更改主题,所以我有每个主题名称的单选按钮,所以你可以假设我可以将 selected 主题名称放入局部变量
var theme = GetThemeNameFromRadioButton();
我正在尝试找出允许用户 select 不同主题(比方说 "Theme2")的最佳方法,这将导致图像看起来像这样
我有不同的主题,我想要一种更改主题的方法
<img src="/Content/Images/Icons/Theme2/title.png" class="slideExampleImage">
<img src="/Content/Images/Icons/Theme2/test.png" class="slideExampleImage">
<img src="/Content/Images/Icons/Theme2/bill.png" class="slideExampleImage">
所以以某种方式进入并更新 src 并将图像下的一个子文件夹(在本例中为 Theme1)替换为选择的新主题(在本例中为 Theme2)
使用 jquery / javascript 实现该目标的方法是什么?请注意,我无法控制主题名称,因为用户可以将主题与任何名称相同
function changeTheme(newTheme) {
// change the "src" attribute
$(".slideExampleImage").attr("src", function(_, oldSrc) {
// split the path
var parts = oldSrc.split(/\//);
// replace the "theme" part of the path with the new one
parts.splice(parts.length - 2, 1, newTheme);
// return/set the new path
return parts.join("/");
});
}