javascript - 查找列表项的子元素

标签 javascript jquery

这是麻烦的函数。我无法正确定位嵌套的 UL 元素:

function showContentAgency(id){
  $.post("assets/includes/contentAgency.php?id=id", {id: id}, function(data){
    $(this).parent().find("ul").html(data).show();
    $(this).addClass("nav-active");
  });
}

点击函数如下:

$("ul.top-level").on("click", "ul.top-level li.agency a", function (event) {
    var numbs = $(this).attr("href").match(/id=([0-9]+)/)[1];
    $("ul.top-level li a").removeClass("nav-active");
    $(this).addClass("nav-active");
    showContentAgency(numbs);
    event.preventDefault();
});

我的 HTML 显示如下:

<ul class="top-level" style="display: block; ">
    <li class="agency"><a href="contentAgency.php?id=6" class="">Agency Name</a>
    <ul>
        <!--Content in here -->
    </ul>
    </li>
</ul>

最佳答案

首先,$.post 的内部成功处理程序 this do 指向它自己的执行上下文。接下来是您必须将 dom 元素传递给 showContentAgency 方法,您可以使用该方法找到所需的 ul 元素。试试这个。

function showContentAgency(id, elem){
   $.post("assets/includes/contentAgency.php?id=id", {id: id}, function(data){
       $(elem).addClass("nav-active").parent().find("ul").html(data).show();
   });
}


$("ul.top-level").on("click", "ul.top-level li.agency a", function (event) {
    var numbs = $(this).attr("href").match(/id=([0-9]+)/)[1];
    $("ul.top-level li a").removeClass("nav-active");
    $(this).addClass("nav-active");
    showContentAgency(numbs, this);
    event.preventDefault();
});

关于javascript - 查找列表项的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9844028/

相关文章:

jquery - 为什么 jQuery 未在我的 Rails 3.2.3 应用程序中加载?

jquery - 多合一横幅---链接图片

javascript - 对 Javascript 数组中的数组中的元素进行排序

javascript - 如何禁用点击选定的数据表jquery?

javascript - 将代码从 jquery 重写为 javascript

javascript - jQuery 中的命名空间?

javascript - 在一段时间内切换(或闪烁)表中的特定单元格

javascript - 在 JavaScript 中的表单字段旁边打印文本

javascript - 使用 jquery 通过 ajax 加载内容

javascript - 监听子集合的变化