Javascript 如何在jQuery中获取下一个或上一个属性ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5396754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get next or previous attribute id in jQuery?
提问by Steffi
I have the following code
我有以下代码
<a class="getty" id="1" href="/...">One<./a>
<a class="getty" id="2" href="/...">Two<./a>
<a class="getty" id="3" href="/...">Three<./a>
When I'll click on Left or right, I'll need to get the previous ID.
Example : If I'm on id="2"
, I need to get id="1"
if I click on left.
当我单击左或右时,我需要获取以前的 ID。
示例:如果我在id="2"
,我需要id="1"
点击左侧才能获得。
$(document).keydown(function(e){
if (e.keyCode == 37) {
$('.getty').attr("id");
return false;
} });
if (e.keyCode == 33) {
$('.getty').attr("id");
return false;
}
});
How can I do that ?
我怎样才能做到这一点 ?
Thanks
谢谢
回答by Hussein
To get the previous id when link is clicked.
单击链接时获取以前的 id。
$('.getty').click(function(e) {
e.preventDefault();
var x = $(this).prev().attr('id');
alert(x);
});
You can do the same for next by using the next()
function
您可以使用该next()
功能对 next 执行相同的操作
Check working example at http://jsfiddle.net/H3hdy/
在http://jsfiddle.net/H3hdy/检查工作示例
回答by Greg
回答by Paul Sham
As GregInYEG mentioned, you need the jQuery next function, but since you are using keys binded to the document, you will also need a way to track which one is the current one.
正如 GregInYEG 所提到的,您需要 jQuery next 函数,但由于您使用的是绑定到文档的键,因此您还需要一种方法来跟踪哪个是当前的。