Home  >  Article  >  Web Front-end  >  IE6/7中getAttribute获取href/src 属性(相对路径0值与其它浏览器不同_javascript技巧

IE6/7中getAttribute获取href/src 属性(相对路径0值与其它浏览器不同_javascript技巧

PHP中文网
PHP中文网Original
2016-05-16 18:02:501260browse

IE6/7中getAttribute获取href/src 属性(相对路径0值与其它浏览器不同的解决方法

测试代码如下: 

 
<a href="/abc/index.html">home</a> 
<img src="http://files.jb51.net/upload/201108/20110828174815833.gif"> 
<script> 
var link = document.getElementsByTagName(&#39;a&#39;)[0]; 
var img = document.getElementsByTagName(&#39;img&#39;)[0]; 
alert(link.getAttribute(&#39;href&#39;)); 
alert(img.getAttribute(&#39;src&#39;)) 
</script>

有元素a和img(标准文档模式),设置了相对路径。各浏览器效果如下

IE6/7:返回完整路径


IE8/9/10/Firefox/Safari/Chrome/Opera:返回相对路径

IE6/7中想要与其它浏览器保持一致的话,可以给getAttribute的第二个参数设为2。

 
<a href="/abc/index.html">home</a> 
<img src="http://files.jb51.net/upload/201108/20110828174815833.gif"> 
<script> 
var link = document.getElementsByTagName(&#39;a&#39;)[0]; 
var img = document.getElementsByTagName(&#39;img&#39;)[0]; 
alert(link.getAttribute(&#39;href&#39;, 2)); // 注意第二个参数 
alert(img.getAttribute(&#39;src&#39;, 2)); // // 注意第二个参数 
</script>

标准的getAttribute方法是没有定义第二个参数的,神奇的IE啊。以下是MSDN对setAttribute参数的描述

IE6/7中getAttribute获取href/src 属性(相对路径0值与其它浏览器不同_javascript技巧

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn