更新时间:2023-10-25 12:05:16
是否建议其他方法?
只需为所有按钮设置一个处理程序,然后为图像ID分别以相同的数字结尾即可.
Just set up one handler for all the buttons, and give the images IDs that end in the same respective number.
然后只需用相同的数字修改图像的src
属性即可切换_black
部分,并从其他部分中删除src
的_black
部分.
Then simply modify the src
attribute of the image with the same number to toggle the _black
portion, and remove the _black
portion of the src
from the others.
HTML
<button id="btn1" >Toggle1</button>
<button id="btn2" >Toggle2</button>
<button id="btn3" >Toggle3</button>
<button id="btn4" >Toggle4</button>
<img class="im1" src="image1_bw.jpg" />
<img class="im1 im2" src="image2_bw.jpg" />
<img class="im2 im3" src="image3_bw.jpg" />
<img class="im4" src="image4_bw.jpg" />
jQuery
$("[id^=btn]").click(function () {
var number = this.id.match(/\d+$/)[0];
var $img = $(".im" + number);
var button = this;
$img.each(function () {
var $th = $(this);
if ($th.is('[src*=_bw]')) {
$th.data('button', button.id);
$th.attr('src', function (i, attr) {
return attr.replace(/_bw/, '');
});
} else if ($th.data('button') == button.id) {
if ($th.not('[src*=_bw]').length) {
$th.attr('src', function (i, attr) {
$th.data('button', null);
return attr.replace(/.jpg/, '_bw.jpg');
});
}
}
});
});
编辑:已更新,以使仅使图像变成彩色的按钮可以将其恢复为黑白.
Updated so that only the button that made an image color can bring it back to black/white.
鉴于与特定按钮相关的图像,似乎我们有几种可能性可以考虑.
It seems that we have several possibilities to consider given the images associated with a particular button.
编写的代码将需要为以下可能的情况纳入足够的逻辑:
The code written will need to incorporate sufficient logic for the following possible scenarios:
单击的按钮具有...
The button clicked has...