最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get next or previous attribute id in jQuery? - Stack Overflow

programmeradmin1浏览0评论

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.

$(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

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.

$(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

Share Improve this question edited Mar 22, 2011 at 22:57 Hussein 42.8k25 gold badges115 silver badges143 bronze badges asked Mar 22, 2011 at 19:31 SteffiSteffi 7,05725 gold badges80 silver badges128 bronze badges 2
  • Hi! You do have a question! Sorry, just thought it was funny ;-P – Bojangles Commented Mar 22, 2011 at 19:33
  • Seriously, with 32 questions you should really know how to format your posts by now. stackoverflow.com/editing-help Edit: And look at what we've done, guys. – BoltClock Commented Mar 22, 2011 at 19:35
Add a comment  | 

3 Answers 3

Reset to default 13

To get the previous id when link is clicked.

$('.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

Check working example at http://jsfiddle.net/H3hdy/

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

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.

发布评论

评论列表(0)

  1. 暂无评论