在加载时运行脚本

时间:2013-02-21 19:11:29

标签: javascript jquery

SO上的某个人帮我写了一个选择框的脚本,它会根据下拉列表中选择的选项显示隐藏的行

function showNext(opt)  {
    takeAway()
    var optMap={
        "Picked Up":"#pickedup",
        "Bus to alternate":"#altad2,#altad1",
        "Walk to alternate":"#altad2,#altad1",
    }
    $(optMap[opt]).css("display","") ;
}

function takeAway(){
    $("#pickedup,#altad2,#altad1").css("display", "none");
}

我需要能够运行onload的东西,所以如果已经选择了某些行,那么显示

以下是受脚本影响的选择

<tr class="~[evenoddrow]"> 
            <td class="bold">In the event of early dismissal I would like my child to:</td><td id="Emergclose_Action">~([01]Emergclose_Action)</td><td class="gwCen"></td>
            <td><select name="eReg|Emergclose_Action" id="eReg|Emergclose_Action" onChange="showNext(value);">
                    <option></option><option value="Walk home as normal">Walk home as normal</option><option value="Ride the bus as normal">Ride the bus as normal</option>
<option value="Picked Up">Be picked up immediately after dismissal</option><option value="Bus to alternate">Ride the bus to an alternate address</option><option value="Walk to alternate">Walk to an alternate address</option>
                </select>           
            </td>
        </tr>

我尝试了以下内容但它没有用。

function showNext(opt)  {
        takeAway()

      var optMap={
             "Picked Up":"#pickedup",
             "Bus to alternate":"#altad2,#altad1",
             "Walk to alternate":"#altad2,#altad1",
              }
           $(optMap[opt]).css("display","") ;       

}
function takeAway(){
    $("#pickedup,#altad2,#altad1").css("display", "none");
 }
$(function(){
   $('#eReg|Emergclose_Action').trigger('onchange');
});

2 个答案:

答案 0 :(得分:0)

尝试从select元素中删除onChange="showNext(value);"并更改ID。在选择器中使用管道|并不是一种好习惯,requires a work-a-round ...如果没有它就更容易了。将其替换为下划线_

所以你选择的html是:

<select name="eReg|Emergclose_Action" id="eReg_Emergclose_Action">

然后以这种方式执行javascript:

$(function(){

   //anything in here will run after the page loads

   //assign showNext to the change event
   $('#eReg_Emergclose_Action').change(function(){
      showNext($(this).val());
   }).change();//manually trigger the change event after its attached

});

答案 1 :(得分:0)

如果某人之前已选择“是”,则必须在页面加载时运行的脚本可以使用Jquery

进行优化,如下所示 。

$( '#EREG | Emergclose_Action')触发( '平变化');