Welcome, Old Sport!


by ilikecss ON 2011/02/23 4118

Website designers and developers have a great many tools at their disposal these days. Like power tools, these things can help or hurt us. In theory, the idea of opening external links in a new window sounds very sane. If everybody used it this idea intelligently, it would be, well, smart.
In fact, I’m surprised my browser doesn’t allow me to specify what to do with links that take me to a different domain. It seems like a reasonable enough expectation.
Moving along, since there’s already scripts out there which set the target attribute to “_blank” and authors who’ve written the tutorials already, so I’ll just get to the point of this script and why it’s different.
Here’s the list of goals and requirements I used in writing this script:
I used jQuery as the base library, but obviously it could be easily translated to another library or to library independence.
Having stalled long enough, and with no further ado, 40 lines of “anchor targeted window scripting” bliss (with attached line-by-line description):

  var extAnchorTarget = function () {
    var msgtxt = null, usropt = null, askopt = null;
    msgtxt = "Click OK to open this link in a new window "
             "or cancel to open it in this window.";
    usropt = $(":radio:checked[name=extwinopt]").val() || 0;
    usropt = parseInt(usropt);
    switch (usropt) {
      case 2:
        this.target = "_blank";
      case 1:
        this.target = "_self";
      case 0:
        askopt = confirm(msgtxt);
        this.target = !askopt ? "_self" : "_blank";
    return true;
  var labelAnchors = function () {
    var winhome = document.domain.split(".").reverse();
        winhome = winhome[1] "." winhome[0];
      var lnkhome = this.href.split("/")[2].split(".").reverse();
          lnkhome = lnkhome[1] "." lnkhome[0];
      if (!winhome.match(lnkhome)) {
      } else {

If you’re using jQuery on your site already, just load this script and all of your target=”blank”-anchors-opening-in-new-windows dreams will come true.
以上说了那么多废话,最重要的想说明如果你的网站上使用了 jQuery,只要加载这个脚本,你的所有链接的目标将会跳转为新窗口打开!

  1. #1


    :sad: 新窗口打开还要加JQ这是可苦呢.