删除后在选定的列表项上添加类
我有一些显示为白框的列表项。然而,数字 60 显示为红色背景。在脚本开始时,我将该列表项的 ID 设置为名为“boxID”的变量。当按下左侧键盘按钮时,该红色背景(类)将被删除,并且“boxID”减去 1,使其变为 59。但是,当我尝试将相同的类添加到包含新“boxID”的列表项时" ID,所有框都变成红色,就好像无法选择 ID #59 的列表项,只能选择全部。
$(document).ready(function(){
var boxID = $('li.selected').attr('id');
$(document).keydown(function(e){
if (e.keyCode == 37) {
$('li').attr('id', boxID).removeClass('selected');
boxID -= 1;
$('li').attr('id', boxID).addClass('selected');
}
});
});
I have a few list items that appear as white boxes. Number 60 appears with a red background, however. At the start of the script I set that list item's ID into a variable called "boxID". When the left keyboard button is pressed this red background (class) is then removed, and the "boxID" is subtracted by 1, making it 59. However, when I try to add the same class to the list item containing the new "boxID" ID, all boxes become red, as if it is unable to select list item with ID #59 and just selects all.
$(document).ready(function(){
var boxID = $('li.selected').attr('id');
$(document).keydown(function(e){
if (e.keyCode == 37) {
$('li').attr('id', boxID).removeClass('selected');
boxID -= 1;
$('li').attr('id', boxID).addClass('selected');
}
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您选择的元素错误。将其更改
为:
按照您编写的方式,您告诉 jQuery 将所有
li
元素的id
属性更改为boxID
,然后将selected
类添加到它们中。You're selecting the element wrong. Change this:
to:
The way you've written it, you're telling jQuery to change all the
li
elements'id
attribute toboxID
, and then after that, add theselected
class to them all.