我正在尝试使用jQuery .load()函数,但我无法让它工作。我正在开发Wordpress插件,并试图根据传入的参数在options上设置一个属性(更具体地说,我试图在选择框上设置默认选项)。
以下是我要做的事:
$("#schedule_timeslot").load(function(){
//execute code to make changes to DOM
//use conditional statements to figure out which DOM to adjust
});下面是HTML:
<select id="schedule_timeslot" name="timeslot">
<option name="8-10" class="schedule_time" value="0" id="ts0">8am - 10am</option>
<option name="10-12" class="schedule_time" value="1" id="ts1">10am-12pm</option>
<option name="12-2" class="schedule_time" value="2" id="ts2" >12pm - 2pm</option>
<option name="2-4" class="schedule_time" value="3" id="ts3">2pm - 4pm</option>
<option name="4-6" class="schedule_time" value="4" id="ts4" >4pm - 6pm</option>
</select>我可以用:
$(window).load(function(){
alert("test");
});有人能告诉我为什么函数不能工作,以及我需要做些什么来执行特定元素上的函数吗?
发布于 2013-11-13 22:40:14
<select>元素不会触发加载事件。加载事件是在与URL关联的元素(通常需要单独的HTTP请求来获取资源)上触发的,例如<script>标记、<img />标记、<iframe>标记等。
要在<select>上触发事件,只需针对文档就绪块中的元素:
$(document).ready(function () {
$("#schedule_timeslot")....
});或者速记,
$(function () {
$("#schedule_timeslot")...
});这将确保DOM已加载并准备就绪,并且当您使用jQuery将其作为目标时(前提是最初加载在页面上,而不是通过ajax加载)。
编辑:
要在文档就绪上调用函数,只需在脚本标记或外部JavaScript表中定义函数即可。在文档就绪块中,调用函数。
例如:
<script type="text/javascript">
function init() {
alert("Hello, I am ready!");
}
$(function () {
init();
});
</script>文档就绪块还提供了应用事件处理程序的位置。由于这些块是在DOM加载完成时触发的,所以您可以确保页面上任何带有初始页面加载(而不是通过ajax)的元素都会出现。
<script type="text/javascript">
$(function () {
$("#schedule_timeslot").on('change', function (e) {
alert("I Changed!");
});
});
</script>编辑:
若要在选中框中设置默认选择,请在.val()中使用jQuery。在document部分中调用.val(),如下所示:
<script type="text/javascript">
$(function () {
$("#schedule_timeslow").val(4);
// This will select
// <option name="4-6" class="schedule_time" value="4" id="ts4" >
// as the option in the select box.
});
</script>https://stackoverflow.com/questions/19965845
复制相似问题