2015-05-30 41 views
0

所以我試圖實現的是一種方法來檢查是否任何元素的父母的href開頭的東西。以下是我已經走了多遠:jQuery如果任何元素的父母的href開頭

$('.element').click(function(e){ 
    if($(this).is('[href^="X"')){ 
     // How to check if the clicked element's href begins with X 
    } 
}); 

但這不是我想要的。我想檢查一下這個元素的父母是否有某個開始的href。

任何想法?

古斯塔夫

+0

可以包括'html'的問題? – guest271314

+0

@ guest271314我不認爲這是解決這個問題所必需的。 –

回答

2

我建議,考慮到嵌套的<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>元素與hrefx開始),那麼評估將返回true,即使它不是一個祖先元素。我認爲這是一個功能–,同時寫出選擇器–,但我忘了在答案本身詳細說明。

如果這被認爲是一個bug,那麼使用parents('a[href^=x]')代替closest('a[href^=x]')的選項將更適合您的使用案例。

參考文獻:

+0

優雅的解決方案,將盡快標誌爲解決方案!歡呼 –

+1

作爲一個側面說明,'最接近()'檢查元素本身。使用'parents()'更有意義,即使我認爲它在OP具體使用情況下並不重要 –

+0

你真的很受歡迎,我很高興得到了幫助! :)而且,@A。Wolff,我沒有提到過,但是我認爲在這種情況下,如果點擊事件可能會傳播到祖先''元素,那麼這將是一個功能(而不是bug)。但是:是的,我應該提到那個,想到了它。 –

1

$(".element").click(function(e) { 
 
    var res = $(this).parents("[href^=X]").is("*"); 
 
    console.log(res); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> 
 
</script> 
 

 
<a href="Xabc123"> 
 
    <div class="element">click</div> 
 
    </a>

+1

我見過很多變種,但從來沒有這個:) –

相關問題