2012-03-23 70 views
1

这是麻烦的功能。我不能正确找到嵌套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> 

回答

5

首先$.post所有内成功处理程序的this指向它自己的执行上下文。接下来,您必须将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(); 
}); 
+0

唉唉!是的,谢谢。它的工作,我欣赏它。 – Yahreen 2012-03-23 17:49:47

+2

+1打我(和我发布相同的东西)。 – 2012-03-23 17:50:28

0

showContentAgency函数是在一个处理程序中,还是它本身?如果是单独的,则this将引用窗口对象,并且$(this)将不会返回任何有意义的内容,并且$(this).parent()将不会执行任何有用的操作。

也许,在点击处理程序中,您应该用showContentAgency.call(this, numbs);替换行showContentAgency(numbs);

+0

在'$ .post'里面,这仍然不是你想要的。你仍然需要将它分配给一个变量。 – 2012-03-23 17:49:55

2

Inside $.post,this不是元素,它是XHR对象,我想。

也尝试通过thisshowContentAgency也。

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

然后:

showContentAgency(numbs, this);