问题描述
当前,我有这个脚本:
<?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脚本.
Which is working, but I'm not sure how to get it out of the foreach
loop so that it doesn't keep repeating the jQuery script over and over again.
总体而言,我正在尝试通过WordPress从get_categories
中获取值,然后从数组中传递name
值,然后在jQuery中进行检查以将一个类添加到div中的特定元素.
Overall, I'm trying to get the values out from the get_categories
via WordPress, but then pass the name
value from the array and then check that within jQuery to add a class to specific elements within a div.
我知道我可能会走错路,所以如果有人知道更好,更清洁的方法,我完全可以提出建议.
I know I'm probably going about the wrong way, so I'm completely open to suggestion if anyone knows a better, cleaner way of approaching this.
推荐答案
使用array_column()获取所有名称.下面未测试的代码
Use array_column() to get all the names. Not tested code below
<?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>
这篇关于将jQuery脚本与WordPress foreach循环一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!