我有一个选择框对象,ajax函数使用所选值作为输入调用OnChange.我还想在首次加载选择框时调用相同的函数.我使用jQuery .load,但是在加载任何选项之前调用了ajax函数,并且我的ajax函数的输入是未定义的.有没有人知道如何让jQuery在调用函数之前等待加载所有选项?
谢谢.
编辑 - 添加代码
我发现一个setTimeout()可以很好地延迟功能.但是,我使用起来很紧张,setTimeout()因为如果页面加载速度比平时慢,则无法正常工作.我尝试$(document).ready按照您的建议替换超时,但在选择选项并且输入未定义之前仍然调用该函数.
这是代码:
<script type="text/JavaScript">
setTimeout('AjaxFunction($("#SelectID option:selected").val()));', 400);
</script>
<select id="SelectID" name="SelectName" onchange="AjaxFunction(this.value);">
<option value='Inland Empire'>Inland Empire</option>
<option value='San Bernardino'>San Bernardino</option>
<option value='Riverside'>Riverside</option>
<option value='California'>California</option>
</select>
Run Code Online (Sandbox Code Playgroud)
gna*_*arf 19
您应该考虑删除onchange=并使用以下方法之一来绑定事件/执行它:
<select id="SelectID" name="SelectName">
<option value='Inland Empire'>Inland Empire</option>
<option value='San Bernardino'>San Bernardino</option>
<option value='Riverside'>Riverside</option>
<option value='California'>California</option>
</select>
<script type="text/JavaScript">
// placing the script after the select SHOULD ensure it executes after the
// select has been created
$("#SelectID").change(function() { // bind a change event:
AjaxFunction($(this).val());
}).change(); // and trigger a "change" event immediately
// If you are using .load to bring #SelectID into existence,
// it would be much better to put the whole segment into the callback of
// .load() as suggested by gaby
$("#sometarget").load("/some-url-with-select-box", function() {
// bind and trigger change event (alternate forms)
$("#SelectID").bind('change', function() {
AjaxFunction($(this).val());
}).trigger('change');
});
</script>
Run Code Online (Sandbox Code Playgroud)
你能展示一些迄今为止的代码吗?使用jQuery的ready()函数应该可以实现你想要的.它基本上等待整个DOM在执行之前加载.
$(document).ready(function(){
//code here runs after the DOM is created
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13634 次 |
| 最近记录: |