2017-05-30 34 views
0

我想在文档的ready()上执行onchange事件。jQuery在加载HTML文档后自动执行事件;

原始功能是onchange=“fucntionname(parms)”;

<select name="country" id="selCountries" onchange="region.changed(this, 1, 'selProvinces')"> 
    <option value="0">{$lang.please_select}{$name_of_region[0]}</option> 
    <!-- {foreach from=$country_list item=country} --> 
    <option value="{$country.region_id}" {if $consignee.country eq $country.region_id}selected{/if}>{$country.region_name}</option> 
    <!-- {/foreach} --> 
</select> 

的Javascript

<script type="text/javascript"> 
    $(document).ready(function(){ 
     var onll=document.getElementsById('selProvinces'); 
     region.changed(onll, 1, 'selProvinces'); 
    }) 
</script> 

错误我得到

document.getElementsById不是在HTMLDocument的一个功能 。

+5

'ElementById'不'ElementsById'你在需要 – user3154108

+0

singurlar它'Element'不是'Elements'.So改变这样使用多种: - '的document.getElementById('selProvinces “);' –

回答

1

正如前面讨论的那样,getElementById中存在拼写错误 - 但是,由于您使用的是jQuery,因此您可以将html和事件处理程序分开以提供更简洁的代码。分离结构和功能总是更好。

<select name="country" id="selCountries"> 
    <option value="0">{$lang.please_select}{$name_of_region[0]}</option> 
    <!-- {foreach from=$country_list item=country} --> 
    <option value="{$country.region_id}" {if $consignee.country eq $country.region_id}selected{/if}>{$country.region_name}</option> 
    <!-- {/foreach} --> 
</select> 


//Javascript 
<script> 
    $(document).ready(function(){ 
     $('#selCountries').change(function(){ 
     var region=$(this).val(); 
     region.changed(region, 1, 'selProvinces'); 
     }) 
    }) 
</script> 
0

如果您已经有jQuery,那么只需使用jQuery函数即可。这些都是很容易记住:

$(document).ready(function(){ 
    $("#selCountries").change();//this will execute whatever onchange already bounded to this element 
}) 
相关问题