2

您必须编写一个函数,根据用户选择的内容“显示”表单的相应部分。例如,如果选择了“Pizza”,则应显示带有有关 Pizza 类型问题的 div #section2。

这是html代码的一部分

<form id="survey" action="#" method="post">

<div id="section1">
    <label for="food">What is your favourite type of food?</label>
    <select id="food" onchange="selection()">
        <option value="pizza">Pizza</option>
        <option value="mex">Mexican</option>
        <option value="thai">Thai</option>
    </select>
</div>
<div id="section2">
    What is your favourite type of pizza?<br>
    <label for="hawaiian">Hawaiian</label><input type="radio" id="hawaiian">
    <label for="supreme">Supreme</label><input type="radio" id="supreme">
    <label for="vegetarian">Vegetarian</label><input type="radio" id="vegetarian">
</div>

我将如何编写一个 javascript 函数,以便当我单击选项比萨时,它将显示第 2 部分?我是一个完整的 javascript 新手,所以任何帮助都会很棒。

4

2 回答 2

3

演示:http: //jsfiddle.net/iambriansreed/rQr6v/

JavaScript:

var sections = {
    'pizza': 'section2',
    'mex': 'section3',
    'thai': 'section4'   
};

var selection = function(select) {

    for(i in sections)
        document.getElementById(sections[i]).style.display = "none";    

    document.getElementById(sections[select.value]).style.display = "block";

}

查看演示。用实际内容替换section3section4div。

于 2012-05-13T13:43:17.447 回答
2

有很多解决方案。最简单的选项之一是稍微更改您的标记并使用divID。

HTML:

<div id="section1">
    <label for="food">What is your favourite type of food?</label>
    <select id="food" onchange="selection(this)">
        <option value="pizza">Pizza</option>
        <option value="mex">Mexican</option>
        <option value="thai">Thai</option>
    </select>
</div>
<div id="section_pizza" style="display: none;">
    What is your favourite type of pizza?<br>
    <label for="hawaiian">Hawaiian</label><input type="radio" id="hawaiian">
    <label for="supreme">Supreme</label><input type="radio" id="supreme">
    <label for="vegetarian">Vegetarian</label><input type="radio" id="vegetarian">
</div>

JavaScript:

function selection(select) {
    document.getElementById("section_" + select.value).style.display = "block";
}

但是,您可以使用JQuery 库并使其更快、更灵活。您可以轻松地将动画添加到块并添加额外的功能。

HTML:

<div id="section1">
    <label for="food">What is your favourite type of food?</label>
    <select id="food">
        <option value="pizza">Pizza</option>
        <option value="mex">Mexican</option>
        <option value="thai">Thai</option>
    </select>
</div>
<div id="section2" data-type="pizza" style="display: none;">
    What is your favourite type of pizza?<br>
    <label for="hawaiian">Hawaiian</label><input type="radio" id="hawaiian">
    <label for="supreme">Supreme</label><input type="radio" id="supreme">
    <label for="vegetarian">Vegetarian</label><input type="radio" id="vegetarian">
</div>

JavaScript:

$("#food").change(function() {
    $("[data-type]").hide();
    $("[data-type='" + this.value + "']").show(1000);
});
于 2012-05-13T13:15:29.367 回答