2012-03-23 72 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);