希望有人能帮助解决我的问题。
我有这样的城市列表:
<ul class="cities">
<li>New York</li>
<li>New York 2</li>
<li>Chicago</li>
<li>Chicago 2</li>
<li>Etc.</li>
</ul>
我想选择以键盘上按下的字符开头的适当城市。例如,如果我按“N”,它将选择“纽约”,如果我再按一次,它将选择“纽约 2”,依此类推。
到目前为止我有 jQuery 代码:
jQuery(document).keypress(function(event){
// Deselect all others
$(".cities li").each(function() {
if($(this).hasClass('active')) {
$(this).removeClass('active');
}
});
$(".cities li").each(function() {
var li_text = $(this).text();
// check if pressed character match first li element character and select it by adding 'active' class
if(li_text.charAt(0).toLowerCase() == String.fromCharCode(event.which).toLowerCase())
{
$(this).addClass('active');
}
});
});
困难在于它正在选择所有具有压制字符的元素。 :(
附注通过选择我的意思是向 li 元素添加“active”类。
最佳答案
为了更有效地实现这一点,您可以在 filter()
中使用正则表达式,它仅返回第一个字符与按键匹配的元素。试试这个:
$(document).on('keypress', function(e) {
var letter = String.fromCharCode(e.which).toLowerCase();
var re = new RegExp('^' + letter, 'i');
$li = $('.cities li').removeClass('active').filter(function() {
return re.test($(this).text().trim());
}).addClass('active');
});
.active { color: #C00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="cities">
<li>New York</li>
<li>New York 2</li>
<li>Chicago</li>
<li>Chicago 2</li>
<li>Etc.</li>
</ul>
关于javascript - 选择以所选字符开头的特定 li 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44482379/