简体   繁体   English

如何在PHP foreach循环中使用jQuery .each()?

[英]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. 我有一个foreach循环,其中包含一个图像数组和一个JS代码,用于添加不同的类,无论宽度是否大于其高度,反之亦然。

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. 问题是if函数获取数组中第一个图像的.width().height()值,并将相同的类添加到.height()所有图像中。

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. 我尝试使用.each() ,当我打印console.log()它给出了第一个图像的值,认识到还有更多,但没有添加特定类。

HTML: HTML:

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

PHP: PHP:

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

JS (jQuery): 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. 您需要从每个图像中获取宽度/高度,因此您需要将其放在foreach循环内。 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');
    }
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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