Jquery在onload上执行onchange事件

我有一个函数,在更改事件时运行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事件。 可能吗? 有没有一个很好的方法来做到这一点?

只需将它放在一个函数中,然后在文档准备就绪,就像这样:

 $(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(); }); 

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

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

如果你将.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(); }); 

要调用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); }); 

另一种方式

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

这对我有用。

  $(function () { $('#checkboxId').on('change', hideShowfunction).trigger('change'); }); function hideShowfunction(){ //handle your checkbox check/uncheck logic here }