Adding class on selected list item after removal
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)开发者_如何学Python.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');
}
});
});
You're selecting the element wrong. Change this:
$('li').attr('id', boxID).addClass('selected');
to:
$('li#' + boxID).addClass('selected');
The way you've written it, you're telling jQuery to change all the li
elements' id
attribute to boxID
, and then after that, add the selected
class to them all.
精彩评论