我有这行PHP代码$data = json_decode($response, true);
和$items = $data['items']
,它是从特定URL返回json数据,如下所示
{
"items": [
{
"family": "ABeeZee",
"variants": ["regular","italic"]
},
{
"family": "Abril Fatface",
"variants": ["regular","400italic","900"]
},
{
"family": "Advent Pro",
"variants": ["100","200","300","regular","500","600","700"]
}
]
}
我创建了这个foreach
循环来检索字体系列名称,并将它们放入选择框中,代码可以正常工作。
我想创建另一个选择框,根据每个字体系列检索variants
数据。我想在选择ABeeZee
字体时,“变体”选择框仅显示regular and italic
。当我选择Abril Fatface
字体时,变体选择框仅显示regular,400italic and 900
。我怎么能用jquery做到这一点?
<select name="font-family" id="fonts">
<?php
foreach ($items as $item) {
$font_names = $item['family'];
<option value="<?php echo $font_names; ?>"><?php echo $font_names; ?></option><?php
}
?>
</select>
答案 0 :(得分:1)
您必须创建一个关联数组,其中键是字体,值是变体的数组。
您将其作为Json字符串传递给JavaScript,以便它成为JavaScript对象。
然后,当字体发生变化时,您将获取作为变体的js对象的值,并使用它们填充变体select。
<?php
//the raw json string
$data = json_decode('{"items": [
{
"family": "ABeeZee",
"variants": ["regular","italic"]
},
{
"family": "Abril Fatface",
"variants": ["regular","400italic","900"]
},
{
"family": "Advent Pro",
"variants": ["100","200","300","regular","500","600","700"]
}
]}');
$items = $data->items;
//we need to convert the object into an associative
//array where the family becomes the key and the value
//is an array of variants. This allows us to access
//the variants of a specific font
//$jsItems would become = [
// 'AbeeZee' => ['regular', 'italic'],
// 'Abril Fatface' => ['regular', '400italic', '900'],
// .. etc
$jsItems = [];
foreach($items as $i) $jsItems[$i->family] = $i->variants;
?>
<html>
<body>
<select id="fonts">
<?php foreach($items as $i): ?>
<option value="<?php echo $i->family;?>"><?php echo $i->family;?></option>
<?php endforeach;?>
</select>
<select id="variants"></select>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function(){
var items = <?php echo json_encode($jsItems);?>;
$("#fonts").change(function(){
var selectedFont = $(this).val();
var variants = items[selectedFont];
$("#variants").html('');
for (i = 0; i < variants.length; i++){
$("#variants").append('<option value="'+variants[i]+'">'+variants[i]+'</option>');
}
})
});
</script>
</body>
</html>
答案 1 :(得分:1)
您必须使用PHP代码将当前选定的变体保存在第二个select
标记内。将第二个select
代码框更改为
select
框
<select id="variants" name="<?php echo $bsn_option; ?>[<?php echo $id2; ?>]" class="form-control">
<?php
$currentFont = $YPE_font[$id1];
foreach ($jsItems[$currentFont] as $variants) { ?>
<option value="<?php echo $variants; ?>" <?php echo selected($YPE_font[$id2], $variants, false); ?>><?php echo $variants; ?></option><?php
}
?>