2013-02-20 7 views
22

私はchangeイベントでpostアクションを実行する機能を持っています。Jqueryはonloadでonchangeイベントを実行します

$("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イベントを実行したいと思います。出来ますか? これを行うには良い方法がありますか?

+0

? $( "select#marca")。change();あなたは試してみましたか? – cernunnos

答えて

42

ちょうどそれを置きます関数内では、次のようにドキュメントの準備もできます。

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

私は$(window).load(function(){ $ {function} { $( "select#marca")change(); })を試しましたが、イベントは実行されません。 –

+1

@PaoloRossi ' $(function() 'はすでに**ページロードで実行されています**' $(window).load'の中にラップしないで '' change'イベントを登録してから '' .change' – mattytommo

+0

パーフェクト!ありがとうございました! –

14

あなたが最後に.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(); 
}); 
14

本当に簡単な方法、それはちょうどあなたの変更機能でこのようなの最後に別の.change()イベントをチェーンに:

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

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

を行うための他の方法を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); 
}); 
関連する問題