如何在jQuery中获得下一个或以前的属性id ?

时间:2022-02-23 20:34:48

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

谢谢

3 个解决方案

#1


9  

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/

#2


1  

You can use jQuery's next function to get the next sibling, and prev to get the previous sibling.

您可以使用jQuery的下一个函数来获得下一个兄弟姐妹,并使用prev来获得前一个兄弟姐妹。

#3


1  

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

#1


9  

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/

#2


1  

You can use jQuery's next function to get the next sibling, and prev to get the previous sibling.

您可以使用jQuery的下一个函数来获得下一个兄弟姐妹,并使用prev来获得前一个兄弟姐妹。

#3


1  

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