phpcms 是一个基于 PHP 的内容管理系统(CMS),它提供了丰富的功能来帮助用户快速构建和管理网站。联动菜单(Cascading Menu)是一种常见的用户界面元素,允许用户通过多级菜单选择不同的选项。在 phpcms 中,前台调用联动菜单通常涉及到数据库查询和前端展示。
假设我们有一个地区联动菜单,数据库表结构如下:
CREATE TABLE `regions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent_id` int(11) DEFAULT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
);在 phpcms 中,可以通过以下方式调用联动菜单:
<?php
// 获取所有地区
$regions = $this->db->get('regions')->result_array();
// 递归函数生成联动菜单
function generateMenu($regions, $parentId = 0) {
$menu = [];
foreach ($regions as $region) {
if ($region['parent_id'] == $parentId) {
$children = generateMenu($regions, $region['id']);
if ($children) {
$region['children'] = $children;
}
$menu[] = $region;
}
}
return $menu;
}
$menu = generateMenu($regions);
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>联动菜单示例</title>
</head>
<body>
<select id="province">
<option value="">请选择省份</option>
</select>
<select id="city">
<option value="">请选择城市</option>
</select>
<select id="district">
<option value="">请选择区县</option>
</select>
<script>
const menu = <?php echo json_encode($menu); ?>;
function populateSelect(parentId, selectId) {
const select = document.getElementById(selectId);
select.innerHTML = '<option value="">请选择</option>';
menu.forEach(region => {
if (region.parent_id == parentId) {
const option = document.createElement('option');
option.value = region.id;
option.textContent = region.name;
select.appendChild(option);
}
});
}
document.getElementById('province').addEventListener('change', function() {
const provinceId = this.value;
populateSelect(provinceId, 'city');
document.getElementById('district').innerHTML = '<option value="">请选择区县</option>';
});
document.getElementById('city').addEventListener('change', function() {
const cityId = this.value;
populateSelect(cityId, 'district');
});
populateSelect(0, 'province');
</script>
</body>
</html>通过以上方法,可以有效解决 phpcms 前台调用联动菜单时遇到的问题。
没有搜到相关的文章