0

On a web page, the contents of a div must dynamically change when a particular selection is made from a drop down list. Below is my code, I don't know where I am going wrong? Any help would be appreciated.

<head>
<script type="text/javascript">
function fn()
{
    var x = document.getElementsById("select").selectedIndex;
    var y = document.getElementById("a").innerHTML;

    if (X == "0")
    {
        y = " So.. ur a conman" ;
    }
    else
    {
        y = "oops";
    }
}
window.onload = fn() ;
x.onchange = fn() ;
</script>

<body>
<select name="select" id="select">
<option value="consulting"> Consulting </option>
<option value="industry"> Industry </option>
</select>
<div id="a" style="background-color:blue; width:1200px; height:20px; color:black;">
</div>
</body>
</html>
4

1 回答 1

2
  • Javascript 区分大小写,因此xX. 更改Xx

  • y接收内部 html 的,而不是对内部 html 的引用。这意味着您不能通过y.

  • 分配给 window.onload 时,您当前正在分配函数的返回值。您想分配函数本身,所以它应该是window.onload = fn;.

改进但未经测试的代码:

<script type="text/javascript">

var x = document.getElementsById("select");
var y = document.getElementById("a");

function fn()
{

    if (x.selectedIndex == 0)
    {
        y.innerHTML = " So.. ur a conman" ;
    }
    else
    {
        y.innerHTML = "oops";
    }
}

window.onload = fn ;
x.onchange = fn ;

</script>

另外,请注意您的浏览器有开发者工具,可以告诉您一些错误。根据您用于测试的浏览器,您可能可以按下F12打开这些工具。看看那里的控制台,你会看到类似于'X' is not defined.

于 2012-07-05T12:17:13.700 回答