2012-08-09 64 views
0

我试图根据用户输入从选择下拉框中显示/隐藏各种div。实际上,首先,我试图直接实施jQuery dropdown hide show div based on value中显示的代码,但是我错过了一些简单的东西,它可以防止它在http://www.intertwineimages.com/form2.html的工作,这里是我的完整代码,任何人都可以指出我的方向吗?jquery show/hid div基于下拉

<html> 

<script type="text/javascript"> 
hideAllDivs = function() { 
    $("#hourly").hide(); 
    $("#per_diem").hide(); 
    $("#fixed").hide(); 
}; 

handleNewSelection = function() { 

    hideAllDivs(); 

    switch ($(this).val()) { 
     case '1': 
      $("#hourly").show(); 
     break; 
     case '2': 
      $("#per_diem").show(); 
     break; 
     case '3': 
      $("#fixed").show(); 
     break; 
    } 
}; 

$(document).ready(function() { 

    $("#project_billing_code_id").change(handleNewSelection); 

    // Run the event handler once now to ensure everything is as it should be 
    handleNewSelection.apply($("#project_billing_code_id")); 

}); 
</script> 
<select id="project_billing_code_id"> 
    <option value="">Pick one</option> 
    <option value="1">1-Hourly</option> 
    <option value="2">2-Per Diem</option> 
    <option value="3">3-Fixed</option> 
</select> 

<div id="hourly">Hourly</div> 
<div id="per_diem">Per Diem</div> 
<div id="fixed">Fixed</div> 

</html> 

编辑:纠正代码

<html> 

<script type="text/javascript" src="js/jquery.js"></script> 
<script type="text/javascript"> 
hideAllDivs = function() { 
    $("#hourly").hide(); 
    $("#per_diem").hide(); 
    $("#fixed").hide(); 
}; 

handleNewSelection = function() { 

    hideAllDivs(); 

    switch ($(this).val()) { 
     case '1': 
      $("#hourly").show(); 
     break; 
     case '2': 
      $("#per_diem").show(); 
     break; 
     case '3': 
      $("#fixed").show(); 
     break; 
    } 
}; 

$(document).ready(function() { 

    $("#project_billing_code_id").change(handleNewSelection); 

    // Run the event handler once now to ensure everything is as it should be 
    handleNewSelection.apply($("#project_billing_code_id")); 

}); 
</script> 
<select id="project_billing_code_id"> 
    <option value="">Pick one</option> 
    <option value="1">1-Hourly</option> 
    <option value="2">2-Per Diem</option> 
    <option value="3">3-Fixed</option> 
</select> 

<div id="hourly">Hourly</div> 
<div id="per_diem">Per Diem</div> 
<div id="fixed">Fixed</div> 

</html> 
+0

jQuery的文件,那么它似乎工作。演示http://jsfiddle.net/qzSu6/。顺便说一句,你有没有包含jquery js文件? – 2012-08-09 13:36:29

+0

没错,它在jsfiddle上工作,但我无法让它在我的服务器上工作(http://www.intertwineimages.com/form2.html),想知道为什么它不会。 – Constantino 2012-08-09 13:37:24

+0

我给你的建议是彻底抛弃jQuery并学习如何使用真正的JavaScript。 – John 2012-08-09 13:38:17

回答

2

它,因为你还没有为http://www.intertwineimages.com/form2.html

+0

啊!这是我错过的简单的事情。你能告诉我究竟如何做到这一点或阐明这个问题? – Constantino 2012-08-09 13:40:34

+0

http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery – hsalama 2012-08-09 13:41:51

+0

它很简单。我的firefox上安装了firebug。当我打开网址时,我在萤火虫中发现一个错误,提示'$未定义'。 – 2012-08-09 13:41:52