Jquery在onload上执行onchange事件

时间:2013-02-20 16:12:47

标签: javascript jquery

我有一个函数,在更改事件时运行post操作。

$("select#marca").change(function(){
    var marca = $("select#marca option:selected").attr('value');
    $("select#modello").html(attendere);
$.post("select.php", {id_marca:marca}, function(data){
        $("select#modello").html(data);
    });
});

我想执行此函数onload事件。可能吗? 有没有办法做到这一点?

6 个答案:

答案 0 :(得分:50)

将它放在一个函数中,然后在文档准备就绪时调用它,如下所示:

$(function () {
    yourFunction(); //this calls it on load
    $("select#marca").change(yourFunction);
});

function yourFunction() {
    var marca = $("select#marca option:selected").attr('value');
    $("select#modello").html(attendere);
    $.post("select.php", {id_marca:marca}, function(data){
        $("select#modello").html(data);
    });
}

或者只是在页面加载时调用change

$(function () {
    $("select#marca").change();
});

答案 1 :(得分:26)

非常简单的方法就是将另一个.change()事件链接到你的on change函数的末尾,如下所示:

$("#yourElement").change(function(){
   // your code here
}).change(); // automatically execute the on change function you just wrote

答案 2 :(得分:16)

如果你将.change()添加到结尾,它将在被绑定后立即被调用:

$(function() { 
    $("select#marca").change(function(){
        var marca = $("select#marca option:selected").attr('value');
        $("select#modello").html(attendere);
    $.post("select.php", {id_marca:marca}, function(data){
            $("select#modello").html(data);
        });
    }).change(); // Add .change() here
});

或者将回调更改为实际功能并调用:

function marcaChange(){
    var marca = $("select#marca option:selected").attr('value');
    $("select#modello").html(attendere);
$.post("select.php", {id_marca:marca}, function(data){
        $("select#modello").html(data);
    });
}

$(function() { 
    $("select#marca").change(marcaChange);
    marcaChange();
});

答案 3 :(得分:2)

要调用onload,您可以尝试jQuery:

 $(document).ready(function(){
 onchange();// onload it will call the function
     });

像这样写你的onchange函数,这样就会在onchange发生时调用

function onchange(){
    var marca = $("select#marca option:selected").attr('value');
    $("select#modello").html(attendere);
    $.post("select.php", {id_marca:marca}, function(data){
    $("select#modello").html(data);
});

答案 4 :(得分:1)

另一种方法

 $("select#marca").val('your_value').trigger('change');

答案 5 :(得分:0)

这对我有用。

 $(function () {
    $('#checkboxId').on('change', hideShowfunction).trigger('change');
});

function hideShowfunction(){
//handle your checkbox check/uncheck logic here
}