【发布时间】: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