2011-08-20 38 views
1

我有一個鏈接下拉框這個jQuery函數:語境中jQuery的AJAX功能

function updateCargoDestinations() { 
    $.ajax({ 
     url: "/truckingmanagement/account/getAccountUserCargoDestinations", 
     data: "id=" + this.value, 
     cache: false, 
     success: function(html) { 
     $("#cargoDestination").html(html); 
     } 
    }); 
    } 
    $(document).ready(function() {$("#account").change(updateCargoDestinations);}); 

它的偉大工程,但我也需要功能運行一次頁面加載時使鏈接下拉框將正確填充。我試圖設置上下文中這樣的功能:

context: ("#account")

,但不工作。我該如何做到這一點,所以這個函數運行一次頁面加載和運行時,觀察下拉框改變?

回答

2

this.value設置爲變量,然後檢查undefined。如果undefined設置爲初始填充下拉菜單所需的任何值。

function updateCargoDestinations() { 
    var selectId = this.value; 
    if (typeof selectId === "undefined") { 
     selectId = "whatever_you_need_here"; 
    } 
    $.ajax({ 
     url: "/truckingmanagement/account/getAccountUserCargoDestinations", 
     data: "id=" + selectId, 
     cache: false, 
     success: function(html) { 
     $("#cargoDestination").html(html); 
     } 
    }); 
} 


$(document).ready(function() { 
    updateCargoDestinations(); 
    $("#account").change(updateCargoDestinations); 
}); 

搗鼓未定義檢查:http://jsfiddle.net/kfJvA/1/

+0

你是對的+1 – Rafay

+0

我想我有' 「whatever_you_need_here」'的問題。我想我需要在那裏有一個元素的id,所以我使用'selectId = $(「#account」);'但由於某種原因,這不起作用。這不是jQuery ajax函數的'context'屬性應該處理的內容嗎? – ubiquibacon

+0

@typoknig'$(「#account」)'是元素本身,而不是id。 'selectId =「account」'是什麼工作,但我完全猜測,因爲我不知道你需要什麼價值。把你需要的任何id作爲默認值加載到下拉菜單中。 –