javascript - 将 ajax 请求添加到附加了先前 ajax 请求的元素

标签 javascript php jquery 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>

它适用于第一个列表,但不适用于第二个列表。

我错过了什么?

最佳答案

您不能对不存在的元素使用直接事件。您需要使用委托(delegate)事件来解决这个问题

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

文档可以被当时存在的任何父元素替换。

检查on有关更多详细信息的文档(“直接事件和委托(delegate)事件”部分)

关于javascript - 将 ajax 请求添加到附加了先前 ajax 请求的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28355259/

相关文章:

javascript - 网页上基于 3DSMax .obj/.max 的模型显示与 AJAX 可点击功能集成

javascript - 我不能在 opera、chrome 或 safari 中使用布料

javascript - JQuery - 第一次打勾时显示第二个复选框

javascript - 显示本地存储变量

php - 使用 preg_match 检查字母数字点破折号和下划线的正则表达式是什么?

javascript - 如何包装 HTML 内容?

php - 使用 PDO 类将 MySql 表数据选择到数组中?

php - 浏览器不会从 onclick 事件设置 cookie

javascript - 追加到 Jasmine 中的 'IT'描述名

javascript - Angular http.get API 请求 - 不存在 'Access-Control-Allow-Origin' header