我有一个类别列表,当客户从列表中选择一个类别时,会在其下方创建一个包含该类别子项的新列表,现在我需要添加另一个级别(另一个列表),但我不知道如何添加。 这应该可行,但我猜脚本无法知道该元素是否存在。
到目前为止我的 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>
它适用于第一个列表,但不适用于第二个列表。
我错过了什么?
最佳答案
您不能对不存在的元素使用直接事件。您需要使用委托(delegate)事件来解决这个问题
$(document).on('change', '#cat_select_2' function() { ... }
文档可以被当时存在的任何父元素替换。
检查on有关更多详细信息的文档(“直接事件和委托(delegate)事件”部分)
关于javascript - 将 ajax 请求添加到附加了先前 ajax 请求的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28355259/