我有一些咖啡脚本,我正在使用它为我网站上的所有外部链接添加一个: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"
但是,这不起作用。
我不确定这个jQuery和外部的东西,但如果第一个示例有效,那么如果你想显示为外部链接,你应该只返回true,所以在你的情况下:
jQuery.expr[':'].external = (obj) ->
obj.hostname not in [location.hostname, 'domain.com', 'sub.domain.com']
首先,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
的元素。
最后,我想要的是允许我的特定域的所有子域作为例外。所以 - 将链接分类为外部 但是,如果链接 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