2015-02-05 150 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文档的更多细节(“直接和委托事件”部分)