So I'm working on a Greasemonkey UserScript for Clients From Hell http://clientsfromhell.net/ and I'm stuck on something.
The script allows a user to navigate through posts on the page using the J and K keys. I'm tr开发者_JAVA技巧ying to mimic the site http://9gag.com/ navigation. There are 10 posts on the page and each of them have the class post
so I thought a simple selector would work and give me the posts in an array. This is how I want the code to work:
postScroll = $('.post')[post].offset().top - 25;
So far I've been doing this and it's been working,
postScroll = $('.post:nth-child(' + post + ')').offset().top - 25;
I just wanted to know if there's a right way of doing what I tried in my first code.
You can use .eq(index)
like this:
postScroll = $('.post').eq(post).offset().top - 25;
This gets the jquery object representing the index in the matches array that you passed in. Doing $(selector)[index]
or $(selector).get(index)
both get the DOM element, not the jQuery object, which you'll need for .offset()
.
精彩评论