我建議,考慮到嵌套的<a>
元素是無效的,這樣只能有一個祖先<a>
元素(或沒有祖先<a>
元素,很明顯):
$('.element').click(function(e){
// here we use a terribly-, but meaningfully-, named variable
// to hold the Boolean result of the assessment;
// the assessment looks from the clicked element up through
// the ancestors for the first <a> element matching the
// attribute-starts-with selector ([href^=x])
// this will return either 1 or 0 elements.
// we check the length; if it's equal to 1 then the ancestor
// has an href starting with x, if it's 0 then there is either
// no ancestor <a> element or no ancestor <a> element with a
// href matching the attribute-starts-with selector:
var ancestorAnchorStartsWithX = $(this).closest('a[href^=x]').length === 1;
});
這是值得注意的是,如@A. Wolff did,在下面的評論,即:
&hellip; closest()
[檢查]元素本身。
這意味着,如果點擊的元素本身提供給最接近的選擇相匹配(因此是<a>
元素與href
與x
開始),那麼評估將返回true,即使它不是一個祖先元素。我認爲這是一個功能–,同時寫出選擇器–,但我忘了在答案本身詳細說明。
如果這被認爲是一個bug,那麼使用parents('a[href^=x]')
代替closest('a[href^=x]')
的選項將更適合您的使用案例。
參考文獻:
可以包括'html'的問題? – guest271314
@ guest271314我不認爲這是解決這個問題所必需的。 –