简体   繁体   English

在页面加载时也触发onchange html事件

[英]Trigger onchange html event on page load too

Ok I have a onchange event on a select field. 好的,我在选择字段上有一个onchange事件。 It now works great. 现在效果很好。 When the dropdown "networks" is changed it refreshes the second dropdown. 当下拉列表“网络”更改时,它将刷新第二个下拉列表。 I also want the ajax code at the top to trigger on page load as well as onchange so the second list gets populated. 我还希望顶部的ajax代码在页面加载以及onchange时触发,以便填充第二个列表。 This is due to it being on an edit page. 这是因为它在编辑页面上。 Here is the ajax call im using first 这是首先使用的ajax调用im

function get_cities(networks) {
    $.ajax({
        type: "POST",
        url: "select.php", /* The country id will be sent to this file */
        beforeSend:     function () {
            $("#folder").html("<option>Loading ...</option>");
        },
        //data: "idnetworks="+networks,
        data: "idnetworks="+networks +"&doc="+ <?php echo $row_rs_doc['parentid']; ?>,
        success: function(msg){
            $("#folder").html(msg);
        }
    });
} 

now the two dropdown boxes 现在是两个下拉框

<label for="networks"></label>
<select name="networks" id="networks" onChange='get_cities($(this).val())'>
    <?php
    do {  
    ?>
        <option value="<?php echo $row_rs_net['idnetworks']?>"<?php if (!(strcmp($row_rs_net['idnetworks'], $row_rs_doc['network']))) {echo "selected=\"selected\"";} ?>><?php echo $row_rs_net['netname']?></option>
    <?php
    } while ($row_rs_net = mysql_fetch_assoc($rs_net));
    $rows = mysql_num_rows($rs_net);
    if($rows > 0) {
        mysql_data_seek($rs_net, 0);
        $row_rs_net = mysql_fetch_assoc($rs_net);
    };
    ?>
</select>
<select name="folder" id="folder">
</select>

You can use .trigger() to trigger a change event onto the select-box so the onchange code will be called like it would if the user just switched the option. 您可以使用.trigger()change事件触发到选择框,以便像用户刚切换选项时一样调用onchange代码。

jQuery('#networks').trigger('change');

Just include this into the load event/function for the page. 只需将其包含在页面的加载事件/函数中即可。

jQuery(document).ready(function() {
    jQuery('#networks').trigger('change');
});

I'm not 100% clear what you want but the standard way to do something with JQuery when the page is loaded, is to use 我不是100%清楚您想要什么,但是在加载页面时使用JQuery进行操作的标准方法是使用

$(document).ready(handler)

This waits till the page is "ready" which is better. 这要等到页面“就绪”为止。

So, in your document head you'd have something like this... 因此,在您的文档头中,您将遇到类似这样的信息...

<script type="text/javascript">
$(document).ready( function(){
  do_some_stuff();
});
</script>

Can't you just call get_cities($('#networks').val()) when the DOM is ready? 当DOM准备就绪时,您不能只调用get_cities($('#networks').val())吗?

$(function() { // will be run by jQuery when DOM is ready
  get_cities($('#networks').val());
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM