我有一个类别列表,当客户端从列表中选择一个时,会在它下面创建一个新列表,其中包含该类别的子级,现在我需要添加另一个级别(另一个列表),但我不确定如何添加。这应该有效,但我想脚本无法知道元素是否存在。
到目前为止,我的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>
它适用于第一个列表,但不适用于第二个列表。
我错过了什么?
不能对不存在的元素使用直接事件。您需要使用委托事件来解决此
$(document).on('change', '#cat_select_2' function() { ... }
Where文档可以被当时存在的任何父元素替换。
查看文档以了解更多详细信息("直接和委托事件"部分)