jquery jump to next element

2019-09-15 11:35发布

问题:

I'm trying to use the jquery next function to click a link to navigate to the next element in an unordered list. What I have is below, but I get a 404 saying it couldn't find [object Object]

$('.next').click(function (event) {
    window.location = $('li').next();
});

and

<div id="nextButton"><a href="#" class="next" id="next">&gt;</a></div>

回答1:

If you posted your code exactly as is, there are a lot of syntax errors. A fixed up version is below:

$('.next').click(function (event) { // missing $/jQuery
    window.location = $('li').next();
}); // missing the close parentheses

In addition, since you are doing things with jQuery, you might want to consider using something like:

// where selector is the selector for the element you are scrolling to
$(window).scrollTop(selector.position().top); 

EDIT

If it's horizontal, you should only need to adjust the scroll code accordingly. e.g.:

$(window).scrollLeft(selector.position().left); 

EDIT #2

Here is a very basic example of what I think you are trying to achieve:

http://jsfiddle.net/FsjkM/

Click the HTML portion and it'll scroll to the next list element (note the changing numbers).

In your actual application you will need to keep track, or calculate, the "current" element to allow for previous/next functionality.

Final EDIT

http://jsfiddle.net/FsjkM/1/

I've fleshed it out a bit to give you an idea of how a more complete structure will look. Note that no boundary checking exist -- if you click prev at the start, or next at the end, it'll break.



回答2:

There are several issues with your code.

  1. $('li') will return all 'li' elements so $('li').next() will return an array. You need selector to indicate current selection.

  2. next() will return an element, it is not necessarily internal html. you might want to use next().html() I think that was your intent. But it does not mean it will work. Continue reading next. :-)

  3. window.location accepts url string (e.g., "http://www.google.com") , not html link (e.g., <a href="http://www.google.com">Google</a>)

Hope it helps