所以從底部元素,我會認爲你在事件處理程序已經收到了,所以我會打電話給this
(原始元素)開始:
如果希望所有其他.div-page.active
元素根據最近的.body-viewport
任何地方,我覺得你的表情是相當多的最好辦法:
$(this).closest(".body-viewport").find(".div-page.active");
如果你只需要.div-page.active
元素是祖先this
(不是兄弟姐妹或堂兄弟等),那麼你將不得不編寫一個循環,jQuery沒有「找到我所有的祖先匹配選擇器X並停止選擇器Y的匹配」。例如,像(live example):
$("#target").click(function() {
var done = false;
$(this).parents().filter(function() {
var $this;
if (done) {
return false;
}
$this = $(this);
if ($this.hasClass("body-viewport")) {
done = true;
return true;
}
else {
return $this.hasClass("div-page") && $this.hasClass("active");
}
}).add(this).css("color", "green");
display("Matches turned green.");
return false;
});
在這個例子中,當您單擊最下面.div-page.active
,原來的那一個,在.div-page.active
幾個級別了,和.body-viewport
綠色。像這樣(在下面粗體顯示的比賽,不能對SO顏色),注意,我添加了一個不相關的.div-page.active
和一個表弟,以顯示他們是如何不包括:
body-viewport
div-page active -- ancestor, should be included
div-panel
div-page
div-page
div-page
div-page active -- click me
div-page active -- cousin, should NOT be included
body-viewport
div-page active -- unrelated, should NOT be included
jQuery的文檔包含一些重要關於最近和父母之間差異的信息。以防萬一,人們想知道爲什麼你選擇最接近父母http://api.jquery.com/closest/ – mrtsherman
你提出的方法有什麼問題?你想避免什麼?如果你必須一遍又一遍地輸入,把它包裝在一個jQuery插件中。 –