首页 > 解决方案 > 在 WordPress foreach 循环中使用 jQuery 脚本

问题描述

目前,我有这个脚本:

<?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 脚本。

总的来说,我正在尝试get_categories通过 WordPress 获取值,然后通过name从数组中传递值,然后在 jQuery 中检查它以将类添加到 div 中的特定元素。

我知道我可能走错了路,所以如果有人知道更好、更清洁的方法来解决这个问题,我完全愿意接受建议。

标签: javascriptphpjquerywordpressforeach

解决方案


使用 array_column() 获取所有名称。以下未测试代码

<?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>

推荐阅读