【问题标题】:Using jQuery script with WordPress foreach loop在 WordPress foreach 循环中使用 jQuery 脚本
【发布时间】:2019-03-26 17:49:51
【问题描述】:

目前,我有这个脚本:

<?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 中的特定元素。

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

【问题讨论】:

  • 如果您希望它只执行一次,请使用可以切换的标志 ($has_executed = false)。
  • 具体会去哪里?在foreach 循环或其他地方?
  • 我想你说的是不重复将JS代码输出到页面中,而不是不重复执行?将现有的 JS 内容放入一个 JS 函数中,然后将其放置在循环之外的其他位置。使其接受单个参数作为函数的输入。然后在循环内的脚本块中,您唯一需要的 JS 就是调用此函数,在其中将 $things 作为参数传递。然后你已经编写了一次函数,但调用了很多次。毕竟,这就是函数的用途......

标签: javascript php jquery wordpress foreach


【解决方案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>

【讨论】:

  • 实际上这符合预期,谢谢!我会继续搞砸它,因为我可能最终会得到更多数据。
【解决方案2】:

我喜欢尽可能将 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>

【讨论】:

  • 啊,是的。这也是我想知道的。一种遍历数组的方法,但将其存储在变量中。这有帮助,谢谢!
猜你喜欢
  • 2015-06-20
  • 1970-01-01
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
  • 2022-10-17
  • 1970-01-01
  • 2018-11-23
  • 2011-07-12
相关资源
最近更新 更多