这是切换各种灯光的另一种方式。我用的是div而不是图片,但是原理是一样的。在此处查看实际操作:http://jsfiddle.net/vy7wX/3/
$('.stoplight').click(function() {
var lights = ['off','green','yellow','red'];
// find current status
var status = $(this).attr('class').replace('stoplight ','');
// get current position in array
var position = $.inArray(status, lights);
// get new position
var position_new;
// -1 because array index starts with 0
if (position == lights.length-1) {
// if it's at the end, go to the beginning
position_new = 0;
} else {
// else take the next status in the array
position_new = position+1;
}
// get the new status, based on position
var status_new = lights[position_new];
// switch classes
$(this).toggleClass(status+' '+status_new);
});
在您的情况下,您可以做两件事:检查当前图像 src 并检索红绿灯名称或向图像添加一个类,以便您可以直接检索名称。后者可能更容易。
例子:
<img class="stoplight red" src="/Images/Stoplights/redStatus.gif" alt="red light" />
以及更改图片src和发布状态的JS:
$('.stoplight').click(function() {
var lights = ['off','green','yellow','red'];
// find current status
var status = $(this).attr('class').replace('stoplight ','');
// get current position in array
var position = $.inArray(status, lights);
// get new position
var position_new;
// -1 because array index starts with 0
if (position == lights.length-1) {
// if it's at the end, go to the beginning
position_new = 0;
} else {
// else take the next status in the array
position_new = position+1;
}
// get the new status, based on position
var status_new = lights[position_new];
// update image classnames and src
$(this)
.toggleClass(status+' '+status_new);
.attr('src', '/Images/Stoplights/'+status_new+'Status.gif');
// update database
$.post('post.aspx', { recordid: <%= this.Id %>, lightid: this.id, value: status_new });
});
使用它,灯光的起始位置是什么并不重要,您可以根据数据库中的当前状态简单地添加正确的类作为起始位置。
编辑
至于 jQuery 1.3.2。 documentation 表示 .toggleClass 方法是在 1.3 中添加的,它可以同时切换多个类。在网上的其他地方,我发现 1.3 只能处理 one 类,所以我假设该方法本身是在 1.3 中添加的,但它在 1.4 中获得了扩展功能,该功能没有在该页面上记录。
不管怎样,没问题。就像你说的,你可以简单地分别切换这两个类。但是,如果您需要使用该方法两次,则可以改用 removeClass 和 addClass,以便脚本更好地阅读。上一部分的课程更新我也忘记了,所以最后会是这样的:
// update image classnames and src
$(this)
.removeClass(status)
.addClass(status_new)
.attr('src', '/Images/Stoplights/'+status_new+'Status.gif');
// update database
$.post('post.aspx', { recordid: <%= this.Id %>, lightid: this.id, value: status_new
另外,为了减少代码行数,position_new 变量可以这样定义:
// get new position
var position_new = position == lights.length-1 ? 0 : position+1;