JavaScript:如何使 div 的样式依赖于在选择框中选择的选项?

标签 javascript html forms

JavaScript

function displayContent()
    {
        var 1 = getElementById(1);
        var 2 = getElementById(2);
        var 3 = getElementById(3);
        var 4 = getElementById(4);

        if(document.form.list.selectedIndex==0) {
        1.style.display = "block";
        }
        if(document.form.list.selectedIndex==1) {
        2.style.display = "block";
        }
        if(document.form.list.selectedIndex==2) {
        3.style.display = "block";
        }
        if(document.form.list.selectedIndex==3) {
        4.style.display = "block";
        }
    }

HTML

   <form id="form">
    <select onchange="displayContent();" id="list">
                        <option>1</option>
                        <option>2</option>
                        <option>3</option>
                        <option>4</option>
                    </select>
    </form>
    <div id="1">Content1</div>
    <div id="2">Content2</div>
    <div id="3">Content3</div>
    <div id="4">Content4</div>

这是我放在一起的脚本和标记。在此之前我尝试了几种不同的方法,但所有方法都导致相同的非解决方案,就像这个一样。当我更改选择框中的选项时没有任何反应。我错过了什么吗?

默认情况下,所有 div 都设置为 display:none;

谢谢, 乔

最佳答案

您的代码有几个问题,包括 getElementById 中缺少 document.,没有提供您的 formselect 元素的 name 属性,以便您可以在 js 中引用它们,尝试创建一个以整数开头并具有以整数开头的 id 属性的变量。

考虑到所有这些,试试这个:

function displayContent() {
    var div1 = document.getElementById("div1");
    var div2 = document.getElementById("div2");
    var div3 = document.getElementById("div3");
    var div4 = document.getElementById("div4");

    if(document.form.list.selectedIndex==0) {
        div1.style.display = "block";
    }
    if(document.form.list.selectedIndex==1) {
        div2.style.display = "block";
    }
    if(document.form.list.selectedIndex==2) {
        div3.style.display = "block";
    }
    if(document.form.list.selectedIndex==3) {
        div4.style.display = "block";
    }
}

Example fiddle


另请注意,这可以大大简化:

function displayContent() {
    document.getElementById("div" + (document.form.list.selectedIndex + 1)).style.display = "block";
} 

Example fiddle

关于JavaScript:如何使 div 的样式依赖于在选择框中选择的选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10685667/

相关文章:

JavaScript 数组和 MySQL

php - 从 Materialise Form 添加到 MySQL

forms - 如何正确地将 'arrowed' block 附加到上面的输入

php - php中如何比较两个字符串是否相等?

jQuery 处理动态添加元素上的事件

javascript - Webpack 2 + ExtractTexWebpacktPlugin = 意外标记

javascript - 间隔并不总是被清除

javascript - Protractor 中的 browser.ignoreSynchronization 是什么?

javascript - HTML5 文件系统 : How to revoke granted quota?

javascript - PHP、JS、HTML 和 CSS 文件如何在同一页面上协同工作?