我正在尝试让我的图像源属性在单击某个按钮时更改。我现在得到了这段代码。
$('.palettemain #brown').click(function () {
var imageName = $('.panestop span > img').attr('alt');
var imageFolder = 'images/sitebuilder/logo/brown/';
$('.panestop span > img').each(function () {
$(this).attr('src', imageFolder + imageName);
});
});
如您所见,我已为图像名称和图像文件夹声明了变量名称。当我单击.palettemain #brown
(按钮)时,它会加载图像,同时也会获取正确的文件夹名称和图像文件名称。这里的事情是,只获取第一个实例图像文件名。下面是点击发生前的HTML代码。
<span>
<input type="radio" name="logo" checked="checked" />
<img src="images/sitebuilder/logo/default/logo01.png" alt="logo01.png" />
</span>
<span>
<input type="radio" name="logo" checked="checked" />
<img src="images/sitebuilder/logo/default/logo02.png" alt="logo02.png" />
</span>
<span>
<input type="radio" name="logo" checked="checked" />
<img src="images/sitebuilder/logo/default/logo03.png" alt="logo03.png" />
</span>
点击时输出如下:
<span>
<input type="radio" checked="checked" name="logo">
<img alt="logo01.png" src="images/sitebuilder/logo/brown/logo01.png">
</span>
<span>
<input type="radio" checked="checked" name="logo">
<img alt="logo02.png" src="images/sitebuilder/logo/brown/logo01.png">
</span>
<span>
<input type="radio" checked="checked" name="logo">
<img alt="logo03.png" src="images/sitebuilder/logo/brown/logo01.png">
</span>
正如您所看到的,输出正在复制第一个图像alt
属性。如何为图像的每个实例获取alt
属性?
答案 0 :(得分:1)
您只能从alt属性中读取一次图像名称。尝试:
$('.palettemain #brown').click(function () {
var imageFolder = 'images/sitebuilder/logo/brown/';
$('.panestop span > img').each(function () {
imageName = $(this).attr('alt');
$(this).attr('src', imageFolder + imageName);
});
});