我正在编写一个简单的jQuery函数来从html页面中选择一个选择器,而在keypress上(向上或向下)应该为它添加一个CSS类。
问题是它没有检测到添加类的选择器。
HTML选择器嵌套在代码中。
html
body
div.fixed-header
div#main-nav.primary-nav.navbar
div.navbar-inner
div.primary-nav-right-content
ul.nav
li#global-search
div.search-results
ul.search-dropdown
ul.search-entry
我正在尝试在我的jquery中检测选择器ul.search-entry。
我现在在javascript中拥有的是这个。
var selector = $('ul.search-entry');
var selected;
$(window).keydown(function(e){
if(e.which === 40){
if(selected){
selected.removeClass('selected');
next = selected.next();
if(next.length > 0){
selected = next.addClass('selected');
}else{
selected = selector.eq(0).addClass('selected');
}
}else{
selected = selector.eq(0).addClass('selected');
}
}else if(e.which === 38){
if(selected){
selected.removeClass('selected');
next = selected.prev();
if(next.length > 0){
selected = next.addClass('selected');
}else{
selected = selector.last().addClass('selected');
}
}else{
selected = selector.last().addClass('selected');
}
}
else{
}
});
我一直在绞尽脑汁,我知道我错过了一些非常小的东西。有什么想法吗?
答案 0 :(得分:2)
将selector
设置为选择器字符串,而不是结果集合,并在需要时调用jQuery
进行搜索。
var selector = 'ul.search-entry';
var selected;
$(window).keydown(function(e){
if(e.which === 40){
if(selected){
selected.removeClass('selected');
next = selected.next();
if(next.length > 0){
selected = next.addClass('selected');
}else{
selected = $(selector).eq(0).addClass('selected');
}
}else{
selected = $(selector).eq(0).addClass('selected');
}
}else if(e.which === 38){
if(selected){
selected.removeClass('selected');
next = selected.prev();
if(next.length > 0){
selected = next.addClass('selected');
}else{
selected = $(selector).last().addClass('selected');
}
}else{
selected = $(selector).last().addClass('selected');
}
}
else{
}
});