使用带有WordPress foreach循环的jQuery脚本

问题描述 投票:0回答:2

目前,我有这个脚本:

<?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_categories中获取值,但随后从数组中传递name值,然后在jQuery中检查是否为div中的特定元素添加了一个类。

我知道我可能会采取错误的方式,所以如果有人知道一种更好,更清洁的方法,我完全愿意接受这个建议。

javascript php jquery wordpress foreach
2个回答
1
投票

使用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>

0
投票

我喜欢尽可能地将PHP与JS分开,并防止多次迭代。所以我在PHP中处理$names,然后json_encode它为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>
© www.soinside.com 2019 - 2024. All rights reserved.