2015-02-09 83 views
6

我正在研究只安裝jQuery 1.1的應用程序,它不支持.closest方法。Vanilla JavaScript .closest without jQuery

我的劇本目前看起來是這樣的:

$('.navPanel').find('img').closest('td').hide(); 

所以我期待在.navPanel每個圖像和向上遍歷DOM和隱藏,它坐落在TD有誰知道是否有。一個香草JavaScript函數,我可以簡單地添加到我的腳本,填充缺少的.closest方法?

謝謝你的時間。

+0

['。家長()'](http://api.jquery.com/parents/)? – 2015-02-09 09:29:07

+0

http://stackoverflow.com/questions/15329167/closest-ancestor-matching-selector-using-native-dom – BeNdErR 2015-02-09 09:29:23

+0

嗨,應該說,.parent()不會在這個實例中工作,因爲一些頁面, img在它周圍封裝了一個href標籤,它將刪除這個元素而不是td。所以它真的需要找到最接近的td – 2015-02-09 09:31:04

回答

-10

您可以使用.parents()eq選擇器。父母和EQ選擇無論是在1.0版本中加入:

$('.navPanel').find('img').parents('td').eq(0).hide(); 
+4

不是真的香草,所以在技術上它不回答這個問題。但我可以想像OP會對此感到滿意。 'parents()'可以從jQuery 1.0中獲得。 'eq()'只能從1.1.2開始。 – GolezTrol 2015-02-09 09:30:58

+2

@GolezTrol OP要求的是什麼,實現他們想要的最好的方式往往是完全不同的兩件事情。 – 2015-02-09 09:33:38

+0

@GolezTrol:我不確定香草,但是這應該對所有jquery版本都有效,因爲它們已經在版本1.0中添加了,並且從此不再被棄用。 – 2015-02-09 09:33:41

22
myImage.parentNode; 

是因爲香草,因爲它得到。重擊,在一個循環中,直到你點擊所需的標籤類型:

while(thisTag.parentNode.tagName !== 'TD') // uppercase in HTML, lower in XML 
    { 
    thisTag=thisTag.parentNode; 
    } 

這應該在普通的老js中做到這一點。

丹尼

+0

當然,這有一個問題,如果你沒有找到它,並得到「文件」,那麼它會失敗。 :) – Xotic750 2015-02-09 09:58:15

+1

@ Xotic750 - 非常真實的,它會死在可怕的方式,但這是JavaScript;) – allnodcoms 2015-02-09 10:07:45

+2

然後只需添加一個檢查器,如果while已經擊中html標籤,然後跳出循環 – 2015-06-03 07:26:11

3

原因IE仍然不支持element.closest()最簡單的做法是使用polyfill。

包括this js(這是填充工具對最近())

(function (ElementProto) { 
 
\t if (typeof ElementProto.matches !== 'function') { 
 
\t \t ElementProto.matches = ElementProto.msMatchesSelector || ElementProto.mozMatchesSelector || ElementProto.webkitMatchesSelector || function matches(selector) { 
 
\t \t \t var element = this; 
 
\t \t \t var elements = (element.document || element.ownerDocument).querySelectorAll(selector); 
 
\t \t \t var index = 0; 
 

 
\t \t \t while (elements[index] && elements[index] !== element) { 
 
\t \t \t \t ++index; 
 
\t \t \t } 
 

 
\t \t \t return Boolean(elements[index]); 
 
\t \t }; 
 
\t } 
 

 
\t if (typeof ElementProto.closest !== 'function') { 
 
\t \t ElementProto.closest = function closest(selector) { 
 
\t \t \t var element = this; 
 

 
\t \t \t while (element && element.nodeType === 1) { 
 
\t \t \t \t if (element.matches(selector)) { 
 
\t \t \t \t \t return element; 
 
\t \t \t \t } 
 

 
\t \t \t \t element = element.parentNode; 
 
\t \t \t } 
 

 
\t \t \t return null; 
 
\t \t }; 
 
\t } 
 
})(window.Element.prototype);

,然後它就像IE瀏覽器可以理解它,它的工作原理與所有沒有其他變化。

from jonathantneal/closest