开发者

Jquery Parent Child Selector Improvement

I am learning Jquery and hope to do things better. I have found a solution, and want to see how a seasoned veteran would do it... If there is more eloquence, so to speak.

The problem is I have a widget that rests in a table row. The widget has the same classes as all the other 20 widget. When someone clicks on a particular widget, only that widget should change.

Here's the HTML:

<div class="deal-widget">
  <div class="deal-widget-left">
    <div class="deal-widget-left-countdown">
      <span class="totalcoupons">500</span> of <span class="maxcoupons">500</span>
    </div>
    <div class="deal-widget-left-remain">
      Remaining
    </div>
  </div>
  <div class="deal-widget-right is_open">
    <a href="/deal/claim/1113" class="deal-link">Claim It!</a>
  </div>
</div>

Here's my stab at the JQuery:

Drupal.behaviors.plusone = function (context) {
  $('a.deal-link:not(.deal-processed)', context).click(function () {
    var parent = $(this).parents('div.deal-widget');
    var originalVote = parent.children('div.deal-widget-left').children('div.deal-widget-left-countdown').children('span.totalcoupons').text();
    var originalVoteInt =  parseInt(originalVote);
    var voteSaved = function (data) {
      parent.children('div.deal-widget-left').children('div.deal-widget-left-countdown').children('span.totalcoupons').html(originalVoteInt - data.total_votes);
      parent.children('div.deal-widget-right').html(data.voted);
      parent.children('div.deal-widget-right').removeClass('is_open').addClass(data.votedClass);
    }
    $.ajax({
      ty开发者_JAVA技巧pe: 'POST',
      url: this.href,
      dataType: 'json',
      success: voteSaved,
      data: 'js=1'
    });
    return false;
  })
  .addClass('deal-processed');
}

Is there a better way of selecting parent then second set of children to a clicked-upon object than this?

Thanks

Joe


I'd suggest using:

var parent = $(this).closest('div.deal-widget');
var originalVote = parent.find('span.totalcoupons').text();

closest() searches the ancestor elements for the first element that matches the provided selector; find() searches the descendent elements for those that match the provided selector.

While closest() returns only one match (the closest/*first* element that matches the selector) it's important to note that find() may return multiple elements.


References:

  • closest().
  • find().


Use find()? So:

var originalVote = parent.children('div.deal-widget-left').children('div.deal-widget-left-countdown').children('span.totalcoupons').text();

becomes:

var originalVote = parent.find('span.totalcoupons').text();

I'm not sure exactly what you're looking for here...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜