简体   繁体   中英

What is a better alternative to .next() and .prev() when multiple elements are present?

I am using jQuery for a set of voting buttons.

When the up votes is clicked the down vote is deselected and vice versa.

Currently I am using $(this).next(); to get the down vote that is next to the up vote and $(this).prev(); for the up vote when clicking the down vote.

I need a good alternative that would allow me to add other html elements around and close by these two elements without having to worry about the position of the up and down vote breaking jQuery.

There are multiple up and down votes on a page.

Any solutions or ideas?

Example:

<div class="heart btn pull-right click-heart peinto-heart-empty" data-is-clicked="false" data-sketch-id="someid"></div>

<div class="poop btn pull-right click-poop peinto-poop-empty" data-is-clicked="false" data-sketch-id="someid"></div> 

Let's assume that the upvote and downvote buttons are within the same parent element (this will still work if they share a common non-immediate parent that the other upvote/downvote buttons do not share, but the code is a little messier):

<div class="voting-box">
    <button class="upvote" ... >Up!</button>
    <button class="downvote" ... >Down!</button>
</div>

Then we have an on-click handler for upvote:

function onUpvoteClick(event) {
    var downvoteButton = $(event.target).parent().find('.downvote');
    // do something with the downvote button, eg:
    downvoteButton.css('color', 'red');
}

If we add more elements to the .voting-box or change the order of the elements within, this code will still work.

JSFiddle: http://jsfiddle.net/bxLyM/

I'd use something like this

Item 1
<a class="vote" data-id="1" data-direction="up">Vote Up</a>
<a class="vote" data-id="1" data-direction="down">Vote Down</a>

<br>

Item 2
<a class="vote" data-id="2" data-direction="up">Vote Up</a>
<a class="vote" data-id="2" data-direction="down">Vote Down</a>

JS:

$(function() {
  $('a.vote').click(function(e) {
    var id = $(this).data('id');

    //save the vote (via ajax)

    $('a.vote[data-id="' + id + '"]').removeClass('selected');
    $(this).addClass('selected');
  });
});

Here is the JS Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM