我需要编写一段简短的代码,允许文章顶部的用户执行以下操作:
Drop down 1: How old are you?
Drop down 2: What's your favourite fruit?
基于上面的输入,摘要文本在第二次选择之后立即显示在下面,基于以上两种选择。
对喜欢苹果的18-24岁儿童来说:苹果能帮助你在你的年龄建立免疫系统!
对于那些喜欢香蕉的50-60岁的人来说:香蕉在以后的生活中确实对维生素C和骨密度有帮助。
发布于 2016-05-25 08:03:38
这都取决于您的数据是如何构造的。
假设有相当多的年龄和果实,像这样的某种数据结构会起作用:
var text = [
{ fruit: "bananas", ages:
[
{ range: "18-24", text:"Bananas are awesome"},
{ range: "50-60", text:"Bananas really help with vitamin C and bone density in later life."}
]
},
{ fruit: "apples", ages:
[
{range: "18-24", text:"Apples help you build your immune system at your age!"},
{range: "50-60", text:"Apples are cheap."}
]
}
]然后,选择列表的选定值可以用于搜索数据以找到正确的文本:
function findText(fruit,age)
{
for(var i =0; i < text.length; i++)
{
if(text[i].friut == fruit)
{
for(var j=0; j < text[i].ages.length; j++)
{
if(text[i].ages[j].range == age)
return (text[i].ages[j].text;
}
}
}
return "No match";
}然后,如何绑定更改事件,只需调用find函数:
document.getElementById("age").onchange = function()
{
var age= document.getElementById("age").value();
var fruit = document.getElementById("fruit").value();
var displayText = fruitText(friut,text);
}https://stackoverflow.com/questions/37430471
复制相似问题