2009-07-27 114 views
0

问题是什么?超链接不需要的前缀Internet Explorer [Javascript]

只有在Internet Explorer(惊喜)是我的代码执行不正确。下面这段简短的代码应该为每个“a”标签附加一个“onclick”动作。这很奇妙,但看看第五行,它应该将第二个函数参数设置为锚标记的“href”属性的值。在WebKit,Mozilla等中,它很好。如果我们将“href”设置为“lorem_ipsum”,那么WebKit,Mozilla等将检索正确的结果并将第二个函数参数设置为“lorem_ipsum”,Internet Explorer前缀“http://www.some.site/”,因此我们将“http://www.some.site/lorem_ipsum”报告为第二个参数。 Internet Explorer不正确,因为这不是锚标记实际值的“href”属性。

Anchors=Parent.getElementsByTagName("a"); 
Anchor=0; 
while(Anchor<Anchors.length){ 
    Anchors[Anchor].onclick=function(){ 
     Plot("",this.getAttribute("href")); 
     return false; 
    }; 
    Anchor++; 
}; 

我该如何解决这个荒谬的问题?在最后的斜线之前,我需要从字符串中剥离吗?这似乎是一个漫长的啰嗦!有任何想法吗?

回答

1

容易...

Anchors[Anchor].onclick=function() { 
    var href = this.href || this.getAttribute("href"); 
    if(href.indexOf(location.href) >= 0) 
     href = href.substring(location.href.length); 

    Plot("", href); 
    return false; 
}; 
+0

感谢您的快速回复。你能否解释你的答案,以便我可以看到它为什么发生了,以及你如何修复它。 KR,Jay – Jay 2009-07-27 16:12:16

+0

location.href是一个预定义的变量,包含当前窗口的URL。我从链接中获取HREF属性,如果它包含此值,则将其子字符串去掉。简单。 – 2009-07-27 17:12:20

相关问题