javascript - 在 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 中的特定元素。
我知道我可能走错了路,所以如果有人知道更好、更清洁的方法来解决这个问题,我完全愿意接受建议。
解决方案
使用 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>
推荐阅读
- .net - 为什么 SQL Server 的 SQL OLE DB 驱动程序会截断日期时间值的秒数和小数秒?
- javascript - 如何找到特定部分的引导程序
- oracle - 我们可以在 Unix 中通过“exp”命令导出视图吗
- android - 在 Xamarin Android 项目中放置系统参数的位置
- android - 我想刷新数据来自 Firebase 的回收适配器?
- python - 使用 pyodbc 从数据库中检索特定值
- odata - return updated object in xsodata update operation exit
- sql-server - SQL Server 中的数据透视表总和缺失数据
- arangodb - 如何使用 AQL 遍历以获取特定类型的所有子项
- python - AttributeError: type object 'spacy.syntax.nn_parser.array' has no attribute '__reduce_cython__' ,(将路径添加到虚拟环境)