点击动态生成的元素不工作jquery

时间:2014-08-10 16:20:07

标签: javascript jquery html asp.net-mvc asp.net-mvc-4

我在这个link中发现了一些关于这个问题的答案,但它对我不起作用我不知道我是否做了其他错误我正在尝试在页面加载时创建一些html然后单击在动态创建的html元素上,但特定元素上的click事件在这里不起作用是我的代码:

$(function () {

console.log("Category Page Script loaded");

$.post('/Category/GetCategories', {}).success(function (data) {
    console.log(data);

    $Category = $('ul#Category-filter');
    $Category.empty();
    console.log("coustom empty");
    var html = '';

    for (sub in data) {
        console.log(data[sub].CategoryID, data[sub].CategoryName);
        var html = '<li class="dropdown-tree CategorySelected">'
                   + '<a class="dropdown-tree-a"  data-id="' + data[sub].CategoryID + '">' + data[sub].CategoryName + ' COLLECTION </a>'
                   + '<ul class="category-level-2 dropdown-menu-tree" id="' + data[sub].CategoryID + '">'
                   + '</ul>'
                   + '</li>'
        console.log(html);
        $Category.append(html);
    }

}).error(function () {
    console.log('error');
});
//___________________________________________________________________________

$('li.CategorySelected').on('click', function () {

    console.log("clickd");

    // Get the id from the link
    var SelectedCategoryID = $(this).attr("data-id");

    $CategorySelected = $('ul#' + SelectedCategoryID);
    $CategorySelected.empty();

    console.log("CategorySelected empty");

    var html = '';

    if (SelectedCategoryID != '') {

        $.post("/SubCategory/GetSubCategories", { SelectedCategoryID: SelectedCategoryID },
         function (data) {
             console.log(data);

             for (sub in data) {
                 console.log(data[sub].SubCategoryID, data[sub].SubCategoryName);

                 var html = '<li><a href="' + data[sub].SubCategoryID + '">' + data[sub].SubCategoryName + ' </a> </li>'

                 console.log(html);

                 $CategorySelected.append(html);
             }


         });
    }
});

//_________________________________________________________
});

1 个答案:

答案 0 :(得分:2)

$('ul#Category-filter').on('click', 'li.CategorySelected', function(){
    //your scripts here
});