新窗口中的非现场链接脚本,不收集页面中的所有链接

时间:2013-03-26 13:18:02

标签: javascript html

嗨,我是初学者,这是我的第一个问题。

我最近设置了一个网站,并有一些外部链接。默认情况下,所有设置都在同一窗口中打开,但是想让访问者选择切换外部链接以在新窗口中打开。

我找到了来自http://www.dynamicdrive.com/dynamicindex8/newwindow2.htm

的精彩剧本

修改 这是来自dynamicdrive的脚本:

//Open offsite links in new window script- http://www.dynamicdrive.com/
//Created: August 28th, 2007'

var ddwindowlinks={
//1)Enter domains to be EXCLUDED from opening in new window:
excludedomains: ["dynamicdrive.com", "google.com"],

//2) Target for links that should open in a new window (ie: "_blank", "secwin" etc):
linktarget: "_blank",

//3) Specify operating mode ("auto" or "manual"):
mode: "manual",

//4) If mode is "manual", customize checkbox HTML to show to users (Preserve id attribute):
toggleHTML: '<form><input type="checkbox" id="targetcheckbox" checked="checked" /><label for="targetcheckbox">Open off-site links in new window?</label></form>',

//5) If mode is "manual", enable user persistence so the state of the checkbox is remembered?
persist: true,

assigntarget:function(){
    var rexcludedomains=new RegExp(this.excludedomains.join("|"), "i")
    var all_links=document.getElementsByTagName("a")
    if (this.mode=="auto" || (this.mode=="manual" && this.togglebox.checked)){
        for (var i=0; i<=(all_links.length-1); i++){
            if (all_links[i].hostname.search(rexcludedomains)==-1 && all_links[i].href.indexOf("http:")!=-1)
                all_links[i].target=ddwindowlinks.linktarget
        }
    }
    else{
        for (var i=0; i<=(all_links.length-1); i++)
            all_links[i].target=""
    }
    if (this.mode=="manual" && this.persist)
        this.setCookie("dlinktarget", (this.togglebox.checked)? "yes" : "no", 30) //remember user setting for 30 days (set to -1 then reload page to erase cookie)
},

init:function(){
    if (document.getElementById && this.mode=="manual"){
        document.write(this.toggleHTML)
        this.togglebox=document.getElementById("targetcheckbox")
        this.togglebox.onclick=function(){ddwindowlinks.assigntarget()}
        if (this.persist && this.getCookie("dlinktarget")!="")
            this.togglebox.checked=(this.getCookie("dlinktarget")=="yes")? true : false
    }
    if (window.addEventListener)
        window.addEventListener("load", function(){ddwindowlinks.assigntarget()}, false)
    else if (window.attachEvent)
        window.attachEvent("onload", function(){ddwindowlinks.assigntarget()})
},

getCookie:function(Name){
    var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
    if (document.cookie.match(re)) //if cookie found
        return document.cookie.match(re)[0].split("=")[1] //return its value
    return ""
},

setCookie:function(name, value, days){
    var expireDate = new Date()
    //set "expstring" to either an explicit date (past or future)
        var expstring=expireDate.setDate(expireDate.getDate()+parseInt(days))
        document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/"
}

}

ddwindowlinks.init()

结束修改

该脚本适用于文本链接。

示例

<div class="Artistic-Body-P">
    <span class="Artistic-Body-C">
        <a href="http://externallink.com" style="text-decoration:none;">test</a>
    </span>
</div>

但它不适用于div翻转中的链接。 例如:

<div id="div_popup_roll_13" style="position:absolute;left:109px;top:259px;width:76px;height:76px;">
    <a href="http://externallink.com" rev="image1.png~#~-14~#~-15~#~text~#~148~#~-119~#~#949393~#~Tahoma~#~30~#~0~#~1~#~transparent~#~165">
        <img src="image2.png" border="0" width="76" height="76" id="popup_roll_13" alt="">
    </a>
</div>

我已经破了两天如何解决这个问题,但我猜这个事实是我初学者,并没有帮助所以我决定在这里发帖。

thnx提前帮助

修改

这是来自poproll的代码:

(function($){jQuery.fn.poproll=function(settings){var m_bHovering=false;var m_nDivId=0;
var $m_ImageDiv=null;var $m_TextDiv=null;
var eOptions={Img:0,ImgPosX:1,ImgPosY:2,Txt:3,TxtPosX:4,TxtPosY:5,TxtCol:6,TxtFont:7,TxtSize:8,TxtItallic:9,TxtBold:10,TxtBkgrndCol:11,TxtWidth:12};
function ClosePopup(){if($m_ImageDiv!==null){$m_ImageDiv.remove();
$m_ImageDiv=null;if($m_TextDiv!==null){$m_TextDiv.remove();
$m_TextDiv=null}}}function HoverOver(div){m_bHovering=true;var nDivId=$(div).attr('id');
if(nDivId!==m_nDivId){m_nDivId=nDivId;ClosePopup()}if($m_ImageDiv===null){var anchor=$(div).find('a');
var optionArray=$(anchor).attr('rev').split('~#~');
var href=$(anchor).attr('href');
if(href===undefined){$(div).append('<div id="poproll_img" style="position:absolute; left:'+optionArray[eOptions.ImgPosX]+'px; top:'+optionArray[eOptions.ImgPosY]+'px; z-index:100;"><img src="'+optionArray[eOptions.Img]+'" name="popup_roll_2" alt="" style="position:absolute;left:0px;top:0px;"></div>')}else{$(div).append('<div id="poproll_img" style="position:absolute; left:'+optionArray[eOptions.ImgPosX]+'px; top:'+optionArray[eOptions.ImgPosY]+'px; z-index:100;"><a href='+href+'><img src="'+optionArray[eOptions.Img]+'" name="popup_roll_2" alt="" border="0" style="position:absolute;left:0px;top:0px;"></a></div>')}$m_ImageDiv=$('#poproll_img');
if(optionArray[eOptions.Txt].length>0){var fontStyle=optionArray[eOptions.TxtItallic]>0?'italic':'normal';
var fontWeight=optionArray[eOptions.TxtBold]>0?'bold':'normal';$(div).append('<div id="poproll_txt" style="position:absolute; left:'+optionArray[eOptions.TxtPosX]+'px; top:'+optionArray[eOptions.TxtPosY]+'px; width:'+optionArray[eOptions.TxtWidth]+'px; color:'+optionArray[eOptions.TxtCol]+'; font-size:'+optionArray[eOptions.TxtSize]+'; font-family:'+optionArray[eOptions.TxtFont]+'; font-style: '+fontStyle+'; font-weight:'+fontWeight+'; background-color:'+optionArray[eOptions.TxtBkgrndCol]+'; z-index:100;">'+optionArray[eOptions.Txt]+'</div>');$m_TextDiv=$('#poproll_txt')}}}function HoverOut(){m_bHovering=false;window.setTimeout(function(){if(!m_bHovering){ClosePopup()}},100)}this.hover(function(){HoverOver(this)},function(){HoverOut()})}})(jQuery);

2 个答案:

答案 0 :(得分:1)

自己编写代码可能更简洁。请尝试以下方法:

// Grab every <a> tag in the document.
var allTheTags = document.getElementsByTagName('a');

function parseTags(tags) {
    var size = tags.length; // cache the size;

    for (var i = 0; i < size; i++) {
        var tag = tags[i];
        var href = tag.getAttribute('href');
        // Do we have a target attribute? (and, of course, an href attribute)
        if (href && !tag.getAttribute('target')) {
              var ourHostName = window.location.hostname;
              href = href.split('://');
              // Is there a protocol?
              if (href.length > 1) {
                  href = href[1].split('/')[0]; // Get everything before the first /
                  if (href != window.location.hostname &&
                      href != 'www' + window.location.hostname) {
                      // Sometimes, hostname does not have www in it.
                      tag.setAttribute('target', '_blank');
                  }
              }
        }
    }
};

// Call our function.
parseTags(allTheTags);

我们的变量“allTheTags”是一个Nodelist,它会在DOM更新时更新,所以我们总是可以重新运行我们的allTheTags对象每次传递的parseTags函数。这样,如果有动态添加标记的实例,我们就跳过查询DOM。

修改

在考虑poproll功能的情况下,您必须侦听传递给poproll函数的相同翻转事件。因此,在您选择的元素上调用poproll之后,请在同一元素上侦听悬停。

$(someElementYouUseForPoproll).hover(function () {
    parseTags(allTheTags);
}, function() { });

这样,在我们注入了标记之后,这个悬停事件将在下一个内联执行,现在将看到标记在DOM中生成的poproll。

答案 1 :(得分:0)

我解决了我的问题,通过编辑poprol的代码,将href更改为:

<a href="'+href+'" target="_blank">