从JavaScript添加html,但不起作用jQuery切换功能

adding html from javascript but not working jQuery toggle function?

本文关键字:jQuery 功能 不起作用 JavaScript 添加 html      更新时间:2023-09-26

这是我加载HTML的js函数

function getLeftCategories() {
    var id = 3;
    $.getJSON("/api/kategori/getKategoriByTedarikci/" + id, function (data) {
        var obj = jQuery.parseJSON(data);
        $.each(obj, function () {
            if (this.UstKategoriId == null) {
                var kTop =
                    '<li>' +
                        '<a>' + this.KategoriAdi + '<span>+</span></a>' +
                        '<ul id="ulAltKategori">' +
                        '</ul>' +
                   '</li>'
                $("#ulKategoriler").append(kTop);
            }
        });
        $.each(obj, function () {
            if (this.UstKategoriId != null) {
                var sTop =
                    '<li>' +
                        '<a>- ' + this.KategoriAdi + '</a>' +
                    '</li>'
                $("#ulAltKategori").append(sTop);
            }
        });
    });
}

这是我的HTML方面

<div class="box">
<div class="box-heading">Kategoriler</div>
<div class="box-content">
    <div class="box-category">
        <ul id="ulKategoriler">
        </ul>
    </div>
</div>

这是我要切换的脚本函数

$(function () {
    $('.box-category a > span').each(function () {
        if (!$('+ ul', $(this).parent()).length) {
            $(this).hide();
        }
    });
    $('.box-category a > span').click(function (e) {
        debugger;
        e.preventDefault();
        $('+ ul', $(this).parent()).slideToggle();
        $(this).parent().toggleClass('active');
        $(this).html($(this).parent().hasClass('active') ? "-" : "+");
        return false;
    });
    $('.filter-active span').click();
});

如果我从 JavaScript 添加 HTML 切换功能不起作用,我是否缺少第一次加载到页面的内容?

如果这是动态加载的 html,那么您将需要事件委托来处理这个问题

$(document).on('click', ".box-category a > span", function () {
...
}

只需更改脚本:

$('.box-category a > span').click(function (e) {
  debugger;
  e.preventDefault();
  ...
}

$('.box-category').on('click', 'a > span', function (e) {
  debugger;
  e.preventDefault();
  e.stopPropagation();
  ...
}