【问题标题】:How to get onchange Javascript/jQuery functionality to run onload (doesn't work in <body onload>)如何获得 onchange Javascript/jQuery 功能以运行 onload(在 <body onload> 中不起作用)
【发布时间】:2014-08-26 18:23:04
【问题描述】:

I have the following functionality: http://jsfiddle.net/a8ZWx/274/ ...When the third select option is selected, a text-box appears.

但是,如果我要加载已选择第三个选项的页面(例如,在脚本标记中插入“已选择”),则不会出现文本框(请参阅:http://jsfiddle.net/a8ZWx/275/)。我知道这是因为选择不一定会做出改变。

HTML 代码:

<select id="myselect">
<option value="0">One</option>
<option value="1">Two</option>
<option value="2" selected>Three</option>
</select>
<br />
<input type="text" id="txtData" style="display:none;" />

Javascript 代码:

$('#myselect').change(function() {
if($(this).val() == 2)
    $('#txtData').show();
else
    $('#txtData').hide();
});

我的问题是,如何让文本框在加载选择时显示已选择的第三个选项。我尝试将函数插入到body标签的onload中,但没有成功。

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    尝试在页面加载时触发事件:

    $('#myselect').change(function() {
        //...
    }).change();
    

    http://jsfiddle.net/bwjxrhwo/

    【讨论】:

      猜你喜欢
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-10
      相关资源
      最近更新 更多