2014-09-01 51 views
0

我有一些咖啡文字,我正在使用它爲我網站上的所有外部鏈接添加:external僞類。添加:咖啡腳本中的URL外部

jQuery.expr[":"].external = (obj) -> 
    obj.hostname isnt location.hostname 

我想要做的是允許例外,例如

jQuery.expr[":"].external = (obj) -> 
    obj.hostname isnt location.hostname unless obj.hostname is "domain.com" or "sub.domain.com" 

但是,這是行不通的。

回答

0

我不知道這jQuery和外部啄,但如果第一個例子是工作,那麼你,如果你想顯示爲外部鏈接應該只返回true,所以你的情況:

jQuery.expr[":"].external = (obj) -> 
    obj.hostname not in [location.hostname, 'domain.com', 'sub.domain.com'] 
+0

還有一個問題需要跟進 - 我可以設置排除所有.domain.com子域的規則嗎?例如* .domain.com - 沒有全部指定它們? – strangerpixel 2014-09-22 11:25:58

0

首先,x is a or b不測試如果x要麼ab;您正在尋找x is a or x is b。這也可以寫成x in [a, b]無論如何編譯爲相同的東西。

其次後綴unless有點不尋常。 (a) -> b unless c編譯成

function (a) { 
    if (!c) { 
    return b; 
    } 
} 

所以如果c是真實的,該函數返回undefined,這是falsey。所以這會起作用,但我會覺得這很混亂。其中的邏輯是真的:一個鏈接是外部的,只要鏈接目標不是非此即彼location.hostname,「domain.com」或「sub.domain.com」,即

obj.hostname isnt location.hostname and obj.hostname isnt "domain.com" and obj.hostname isnt "sub.domain.com" 

從而可以更簡明地寫爲

obj.hostname not in [location.hostname, "domain.com", "sub.domain.com"] 

注意,也將適用於僞類的東西在那裏obj.hostnameundefined,因爲undefined肯定是不location.hostname。這可能不是你想要的。您可以使用obj.hostname? and obj.hostname not in [...]過濾出根本沒有hostname的元素。

0

在最終我想要的是允許我的特定域的所有子域作爲例外。所以 - 如果鏈接hrefs爲空,它們處理js事件,或者它們指向domain.com的子域,請不要將它們視爲外部鏈接,而是將外部鏈接分類爲外部鏈接。

$.expr[":"].external = (obj) -> 
    h = obj.href 
    typeof h isnt 'undefined' and h.indexOf('#') is -1 and h.indexOf('javascript') is -1 and h.indexOf('domain.com') is -1