开发者

How can i remove a particular javascript action?

For my site I am using the following code

<script type="text/javascript">
    jQuery(document).ready(function($) {
      $("#body a").filter(function() {
        return th开发者_JS百科is.hostname && this.hostname !== location.hostname;
      }).addClass('external').attr("target", "_blank");
    });
</script>

But this is adding the target="_blank" even to my subdomains. How can i exclude my subdomains from getting added with the _blank? Thank you


This naive function removes all but the specified number of domains/subdomains (2, by default):

function removeSubdomain(hostname, keep) {
    return hostname.split(".").slice(-(keep || 2)).join(".")
}

Use it like this:

jQuery(document).ready(function($) {
    var source = removeSubdomain(location.hostname);
    $("#body a").filter(function() {
        return this.hostname && removeSubdomain(this.hostname) !== source;
    }).addClass('external').attr("target", "_blank");
});

Some tests:

removeSubdomain("meta.stackoverflow.com"); // "stackoverflow.com"
removeSubdomain("test.domain.co.uk", 3); // "domain.co.uk"
removeSubdomain("simple.com") // "simple.com"

To test each link against a set of domains, first add a simple set function:

function set() {
    var i, s = {};
    for (i = 0; i < arguments.length; i++)
        s[arguments[i]] = true;
    return s;
}

And update your filter function with this:

return this.hostname && !(removeSubdomain(this.hostname) in 
    set("google.com", "stackoverflow.com", "mysite.net"))


The easiest would be to code your domain name in there:

return !/(\.|^)example.com$/.test(this.hostname);


var parts = window.location.hostname.split('.');
parts.shift();

var my_domain = parts.join('.');

Will always give you the domain + top domain, if you only have a one level subdomain. With more subdomains you have to use shift() for each level down. Not easy to implement a more general solution, because of different numbers of dots in the top domain (co.uk etc.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜