简体   繁体   中英

WordPress - Script inside the loop only works once

I've got this script in my header and this piece of code in my index, inside the post loop :

  $(function() {
    var score = parseInt($('.post-score').text().trim());
    var color = '#de1d1d';
    if (!isNaN(score)) {
      if (score >= 5) {
        color = '#b84e1f';
      }
      if (score >= 7) {
        color = '#26b81f';
      }
      if (score >= 9) {
        color = '#d9e019';
      }
      if (score >= 10) {
        color = '#0cf';
      }
      $('.post-score').css('color', color);
    }
  });
<?php if( in_category( 'reviews') ) : ?>
<div id="post">
  <span class="post-score">
      <?php the_field('customfield'); ?>
  </span>
</div>
<?php endif; ?>

This function changes that custom field text color depending on the number outputted and it is actually working fine, but just once . It's only working for the FIRST POST with a review, and not in every post.

What's wrong with my code?

Try jQuery each: https://api.jquery.com/each/

Right now, your code is only looking at the first .post-score that it finds.

Edit: I've got it working for you here on this fiddle - https://jsfiddle.net/8b53j2ah/1/

That JQuery code is likely only executed once. But you can achieve the same with PHP.

<?php if( in_category( 'reviews') ) :
    $score = get_field('customfield');
    $score_color = '';
    if($score >= 5 && $score < 7) $score_color = 'b84e1f';
      elseif($score >= 7 && $score < 9) $score_color = '26b81f';
      elseif($score >= 9  && $score < 10) $score_color = 'd9e019';
      elseif($score >= 10) $score_color = '0cf';
?>
<div id="post">
  <span class="post-score" style="color: #<?php echo $score_color; ?>">
      <?php the_field('customfield'); ?>
  </span>
</div>
<?php endif; ?>

You may want to use seperate CSS classes instead of the style-attribute.

you could set up a function including the above javascript and then run it under the onchange attribute. Eg. onchange="function()"

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