2015-02-05 121 views
0

我有一個類別列表,當客戶端從列表中選擇一個新的列表創建下面與該類別的子項,現在我需要添加另一個級別(另一個列表),但我不知道如何。 這應該工作,但我想腳本不能知道元素是否存在或不存在。添加ajax請求到元素附加上一個AJAX請求

到目前爲止,我的JS是這樣的:

<script> 
// when the user clicks on a drop down item from the list it adds a new drop down list 
$('#cat_select_1').on('change', function() { 

    // fetch second list from the other script 
    var fetchUrl = 'http://localhost/includes/ajax/list-of-cats.php?catid='; 
    var fetchCatId = $("#cat_select_1").val(); 

    // if the second list is there 
    if ($("#cat_select_2").length){ 

     // replace it with the new one 
     $.get(fetchUrl.concat(fetchCatId)).done(function(data) { $("#cat_select_2").html(data); }); 
    } 
    else { 
     // otherwise append this one 
     $.get(fetchUrl.concat(fetchCatId)).done(function(data) { $("#jumbocats").append(data); }); 

    } 

}); 

//list #2 (not working) 
$('#cat_select_2').on('change', function() { 

    // fetch third list from the other script 
    var fetchUrl = 'http://localhost/includes/ajax/list-of-cats.php?catid='; 
    var fetchCatId = $("#cat_select_2").val(); 

    // if the third list is there 
    if ($("#cat_select_3").length){ 

     // replace it with the new one 
     $.get(fetchUrl.concat(fetchCatId)).done(function(data) { $("#cat_select_3").html(data); }); 
    } 
    else { 
     // otherwise append this one 
     $.get(fetchUrl.concat(fetchCatId)).done(function(data) { $("#jumbocats").append(data); }); 
     } 
}); 

</script> 

它適用於第一個列表中,但它不會爲第二個列表工作。

我錯過了什麼?

回答

2

您不能對不存在的元素使用直接事件。您需要使用委託事件來解決此問題

$(document).on('change', '#cat_select_2' function() { ... } 

其中,文檔可以被當時存在的任何父元素替換。

檢查on文檔的更多細節(「直接和委託事件」部分)