Jquery在onload上执行onchange事件

Pao*_*ssi 31 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);
    });
});
Run Code Online (Sandbox Code Playgroud)

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

mat*_*mmo 53

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

$(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);
    });
}
Run Code Online (Sandbox Code Playgroud)

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

$(function () {
    $("select#marca").change();
});
Run Code Online (Sandbox Code Playgroud)


ste*_*rie 35

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

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


Ric*_*ton 18

如果添加.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
});
Run Code Online (Sandbox Code Playgroud)

或者将回调更改为实际函数并调用:

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();
});
Run Code Online (Sandbox Code Playgroud)