为什么. nextall()没有返回预期的元素?

Why is .nextAll() not returning the expected elements?

本文关键字:元素 返回 nextall 为什么      更新时间:2023-09-26

我是Javascript/jQuery的新手。只是试图理解什么是错误的以下代码?:

Javascript:

$('.rating-stars').each(function() {
    var currentScore = $(this).nextAll('.current-score');
    console.log(currentScore);
    $('.rating-stars').barrating('show', {
        theme: 'fontawesome-stars-o',
        deselectable: false,
        showSelectedRating: false,
        initialRating: currentScore,
    });
});
HTML:

<form id="vote_form" class="form-inline" method="post" action="/y/update_rating/39">
  <span class="h3"><a href="#">Title</a></span>             
    <select class="rating-stars" id="id_vote" name="vote">
      <option value=""></option>
      <option value="1"></option>
      <option value="2"></option>
      <option value="3"></option>
      <option value="4"></option>
      <option value="5"></option>
    </select>
  <span class="current-score">4.0</span>
</form>

简而言之,我有一个类为.rating-stars的元素,它旁边有一个类为.current-score 的元素,该元素显示一个分数/整数。

我想将initialRating设置为.current-score元素显示的数字。

(正如您可能从代码中猜到的那样,页面上显示的评级不止一个,因此使用.each函数)

当前,console.log返回:

[选择# id_vote。评级星级,上下文:选择#id_vote。rating-stars] 0:选择# id_vote。rating-starscontext:选择# id_vote。[0] [color = 0]ratings.js: 7(选择# id_vote。

在评论的帮助下,我想出了一个解决方案:

我误解了。next() -我没有意识到它只查找兄弟姐妹,我以为它实际上是从上到下读取所有内容,而不是以分层的方式。

我只需要在。next或。nextall调用之前将。parent()添加到变量中:

var currentScore = $(this).parent().next('.current-score').html();

Try This -

HTML

<form id="vote_form" class="form-inline" method="post" action="/y/update_rating/39">
  <span class="h3"><a href="#">Title</a></span>             
    <select class="rating-stars" id="id_vote" name="vote">
      <option value=""></option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
      <option value="5">5</option>
    </select>
  <span class="current-score">3.0</span>
</form>

Jquery

$('.rating-stars').each(function() {
    var currentScore = $(this).next('.current-score').text();
    console.log(currentScore);
    $(this).barrating('show', {
        theme: 'fontawesome-stars-o',
        deselectable: false,
        showSelectedRating: false,
        initialRating: currentScore,        
    });
});

链接到JSFiddle

我认为在你的情况下.next()将工作:

注意:你正在尝试得到元素,但你需要得到元素html或文本。

$('.rating-stars').each(function() {
    var currentScore = $(this).next('.current-score').html();
    console.log(currentScore);
    $('.rating-stars').barrating('show', {
        theme: 'fontawesome-stars-o',
        deselectable: false,
        showSelectedRating: false,
        initialRating: currentScore,
    });
});