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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:01:00  来源:igfitidea点击:

How to get next or previous attribute id in jQuery?

javascriptjqueryajaxattributesjquery-attributes

提问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

You can use jQuery's nextfunction to get the next sibling, and prevto get the previous sibling.

您可以使用 jQuery 的next函数获取下一个兄弟,并使用prev获取前一个兄弟。

回答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 函数,但由于您使用的是绑定到文档的键,因此您还需要一种方法来跟踪哪个是当前的。