Javascript 在WordPress foreach循环中使用jQuery脚本

Javascript 在WordPress foreach循环中使用jQuery脚本,javascript,php,jquery,wordpress,foreach,Javascript,Php,Jquery,Wordpress,Foreach,目前,我有以下脚本: <?php $test = get_categories('taxonomy=item&type=things');?> <?php foreach($test as $stuff) : ?> <script type="text/javascript"> jQuery(document).ready(function($) { var $things = <?p

目前,我有以下脚本:

<?php $test = get_categories('taxonomy=item&type=things');?>

    <?php foreach($test as $stuff) : ?>
        <script type="text/javascript">
        jQuery(document).ready(function($) {
          var $things = <?php echo json_encode($stuff->name); ?>;
          console.log($things);
          $(".element").each(function() {
            var $state = $(this).attr("title");
            if ($things.indexOf($state) > -1) {
              $(this).addClass('current');
            }
          });
        });
        </script>
    <?php endforeach; ?>
这是可行的,但我不知道如何将它从foreach循环中释放出来,这样它就不会一次又一次地重复jQuery脚本

总的来说,我试图通过WordPress从get_类别中获取值,但随后从数组中传递name值,然后在jQuery中进行检查,以将类添加到div中的特定元素


我知道我可能走错了方向,所以如果有人知道更好、更干净的方法,我完全愿意接受建议。

使用array\u列获取所有名称。下面没有测试代码

<?php 
$test = get_categories('taxonomy=item&type=things');
$names = array_column($test, 'name'); ?>

<script type="text/javascript">
jQuery(document).ready(function($) {
  var $things = <?php echo json_encode($names); ?>;
  console.log($things);
  $(".element").each(function() {
    var $state = $(this).attr("title");
    if ($things.indexOf($state) > -1) {
      $(this).addClass('current');
    }
  });
});
</script>

我喜欢尽可能地将PHP与JS分开,并防止多次迭代。因此,我在PHP中处理$names,然后对其进行json_编码以供JS部分计算。下面的代码未经测试

<?php
  $test = get_categories('taxonomy=item&type=things');

  foreach ($test as $stuff) {
    $names[] = $stuff->name;
  }
?>
<script type="text/javascript">
  jQuery(document).ready(function($) {
    var $things = <?php echo json_encode($names); ?>;
    console.log($things);
    $(".element").each(function() {
      var $state = $(this).attr("title");
      if ($things.indexOf($state) > -1) {
        $(this).addClass('current');
      }
    });
  });
</script>

如果您希望它只执行一次,那么使用一个标志$has_executed=false,它可以进行切换。具体到哪里?在foreach循环中还是在其他地方?我想你说的是不要重复地将JS代码输出到页面中,而不是不重复地执行它?将现有的JS内容放入一个JS函数中,将其放置在循环之外的其他位置。使其接受单个参数作为函数的输入。然后在循环中的脚本块中,惟一需要的JS就是调用这个函数,在这里传递$things作为参数。然后,我们编写了一次函数,但调用了很多次。这就是函数的用途,毕竟…实际上,这是我们想要的,谢谢!我会继续搞乱它,因为我可能会有更多的数据,最终可能会回来。啊,是的。这也是我想知道的。循环遍历数组的一种方法,但将其存储在变量中。这有帮助,谢谢!