我有一些coffeescript我用来向我网站上的所有外部链接添加:external
伪类。
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 :(得分:0)
首先,x is a or b
不会测试x
是a
还是b
;你正在寻找x is a or x is b
。这也可以写成x in [a, b]
,无论如何都会编译成相同的东西。
其次,后缀unless
有点不寻常。 (a) -> b unless c
编译为
function (a) {
if (!c) {
return b;
}
}
因此,如果c
为真,则函数返回undefined
,这是假的。所以这会奏效,但我发现这令人困惑。逻辑确实如此:只要链接目的地不是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.hostname
为undefined
的内容,因为undefined
当然不是location.hostname
。这可能不是你想要的。您可以使用obj.hostname? and obj.hostname not in [...]
来过滤掉根本没有hostname
的元素。
答案 1 :(得分:0)
我不确定这个jQuery和外部的东西,但如果第一个例子正在工作那么你只应该返回true如果你想显示为外部链接,所以在你的情况下:
jQuery.expr[':'].external = (obj) ->
obj.hostname not in [location.hostname, 'domain.com', 'sub.domain.com']
答案 2 :(得分:0)
最后我想要的是允许我的特定域的所有子域作为例外。所以 - 如果链接hrefs为空,它们处理js事件,或者它们指向domain.com的子域,不将它们视为外部链接,则将链接分类为外部BUT。
$.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