简体   繁体   中英

How to use jQuery .each() in PHP foreach loop?

I have a foreach loop with an array of images and a JS code to add a different classes whether the width is greater than its height and vice versa.

The problem is that the if function get the .width() and .height() values of the first images in the array and add the same class to all the images that follows.

I try to use .each() and when I print console.log() it gives the value of the first image, recognize that there are more but not add them the spesific class.

HTML:

<?php foreach ( $feedback as $feed ): ?>
  <img class="img" src="<?php echo $feed['pic']; ?>">
<?php endforeach; ?>

PHP:

<?php
  $feedback = [
    [
      'pic' => '1.jpg',
    ],
    [
      'pic' => '1.jpg',
    ],
    [
      'pic' => '1.jpg',
    ],
    [
      'pic' => '1.jpg',
    ],
  ]

JS (jQuery):

$(document).ready(function() {
  var img = $('.img');
  var img_w = img.width();
  var img_h = img.height();
  img.each(function() {
    if ( img_w > img_h ) {
      $(this).addClass('port');
    } else {
      $(this).addClass('land');
    }
  });
});

You're only getting the first image's width/height because they are outside of the function. You need to get the width/height from each image, so you need to put it inside of the foreach loop. Also, it's more efficient to not make it into a variable since you're only using the width and height once per image.

$(document).ready(function() {
  var img = $('.img');

  img.each(function() {
    if ( $(this).width() > $(this).height() ) {
      $(this).addClass('port');
    } else {
      $(this).addClass('land');
    }
  });
});

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