我有以下代码,模拟单击左键或右键按下事件。这用作图库幻灯片的一部分:
$(document).keydown(function (e) {
if(e.keyCode == 37) { // left
$(".thumb-selected").prev().trigger('click');
}
else if(e.keyCode == 39) { // right
$("thumb-selected").next().trigger('click');
}
});
本质上,它选择下一个或上一个同级图像(取决于按下的键)并调用点击事件,该事件将依次在图库中显示适当的图像。这些图像都存储在一个无序列表中。
Where I am stumped is that when the first or last image is selected and the left or right button is clicked (respectively), I want it to get the next picture at the opposite end of the list of images.例如,如果选择了第一张图像并按下了向左箭头;假设没有上一张图片(或 li 元素),它将获取列表中的最后一张图片。这样按键就不会失去功能。
jquery 中是否有一个函数可以检查当前元素是其父元素的第一个还是最后一个子元素,或者返回其相对于其父元素的索引,以便我可以将其索引与 size() (子元素计数)进行比较他的父元素?
最佳答案
您可以使用 is()
[docs]测试方法:
if( $(".thumb-selected").is( ':first-child' ) ) {
// whatever
} else if( $(".thumb-selected").is( ':last-child' ) ) {
// whatever
}
关于javascript - 如何确定元素是 javascript/jquery 中父元素的最后一个还是第一个子元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7533604/