gpt4 book ai didi

php - 根据下拉菜单更改 HTML 选择的内容

转载 作者:行者123 更新时间:2023-11-28 10:24:22 24 4
gpt4 key购买 nike

我有一个选择项目,其中包含文件列表。该文件列表存储在 php 变量中。

我有另一个文件列表,来自另一个目录,存储在另一个变量中。

我有一个下拉菜单,有 2 个选项。当我更改下拉列表时,我希望选择中的项目更改为与所选项目关联的文件列表。

例如,我的下拉列表包含:

  • 杂项图片
  • 人员

我有 2 个变量,$misc$people

当选择 Misc 时,我希望选择包含 $misc 中列出的所有图像,当选择 People 选项时,我希望选择包含 中列出的所有选项$人

就循环遍历 php 来生成所有项目没问题,我不明白的是如何执行 javascript 部分?

谢谢,并对措辞不当表示歉意。

最佳答案

试试这个代码。

PHP:

<?php
$miscArray = array("misc1", "misc2", "misc3");
$misc = implode(", ", $miscArray);
$peopleArray = array("people1", "people2", "people3");
$people = implode(", ", $peopleArray);
?>

HTML:

<form action="#">
<select id="fileCat">
<option id="misc">Misc</option>
<option id="miscData" style="display:none"><?php echo $misc ?></option>
<option id="people">People</option>
<option id="peopleData" style="display:none"><?php echo $people ?></option>
</select>
<select id="files"></select>
</form>

JS:

init();

function init()
{
addListeners();
}

function addListeners()
{
document.getElementById("fileCat").onchange = fillSelect;
}

function fillSelect()
{
var fileCat = document.getElementById("fileCat");
var imageFiles;
switch(fileCat.options[fileCat.selectedIndex].id)
{
case "misc":
imageFiles = document.getElementById("miscData").innerHTML.split(", ");
break;
case "people":
imageFiles = document.getElementById("peopleData").innerHTML.split(", ");
break;
}
var parent = document.getElementById("files");
parent.innerHTML = "";
if(imageFiles.length)
{
for(var i=0;i<imageFiles.length;i++)
{
var option = document.createElement("option");
//populate option with corresponding image text
option.innerHTML = imageFiles[i];
parent.appendChild(option);
}
}
}

我在 PHP 中模拟了一些数据,然后将其回显到隐藏的 <option> 中。每个类别的标签。然后,根据所选选项的 id 使用 case/switch 抓取数据。

关于php - 根据下拉菜单更改 HTML 选择的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4819058/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com