【问题标题】:SCRIPT5007: Unable to set value of the property 'href': object is null or undefinedSCRIPT5007:无法设置属性“href”的值:对象为空或未定义
【发布时间】:2013-11-01 20:35:37
【问题描述】:

此代码不适用于 IE,但适用于 chrome 和 firefox。

我收到此错误消息 IE 控制台:SCRIPT5007: Unable to set value of the property 'href': object is null or undefined

<script>
$(document).on("ready", alternar_banner);

array_imagen = new Array(2);
array_imagen[0] = new Image(108,225);
array_imagen[0].src = "banner1.gif";
array_imagen[1] = new Image(108,225);
array_imagen[1].src = "banner2.gif";

array_url = new Array(2);
array_url[0] = 'http://www.google.com';
array_url[1] = 'https://www.yahoo.com';

contador = 0;

function alternar_banner(){ 
    window.document["banner"].src = array_imagen[contador].src;
window.document.links["bannerref"].href = array_url[contador];
contador ++;
contador = contador % array_imagen.length; 
setTimeout("alternar_banner()",6000);
}

</script>

<a name="bannerref" href="#"><img src="#" name="banner" width=108 height=225 border=0></a>

【问题讨论】:

  • 缺少相关的HTML代码。
  • 在你的 DOM 中是否有 ID 为 bannerref 的链接?如果有,是否有 href 标记?

标签: javascript php jquery html internet-explorer


【解决方案1】:

document.links 返回带有 href 属性的锚点集合,如果您没有与锚点关联的 href 属性,则它不会将其作为集合的一部分返回。

links 属性返回文档中所有 AREA 元素和锚元素的集合,并带有 href 属性的值。

所以这可能是几件事:

  • 您要查找的元素的 ID/名称不是 bannerref
  • 它没有href 属性。

更新标记问题更新后

似乎 IE 中的 document.links 需要使用索引来引用,例如:window.document.links[0].href 但您不能依赖它,因为在此之前可能会出现更多锚点。如果这是唯一的具有名称的锚实例,请尝试使用以下内容:

 document.getElementsByName("bannerref")[0].href = array_url[contador];

或为该锚提供一个 ID 为 bannerref

document.getElementById("bannerref").href = array_url[contador];

或者您也可以使用 jquery 来获取元素并将属性设置为它。

并更好地使用为setTimeout提供函数引用的做法

   setTimeout(alternar_banner,6000);

【讨论】:

  • 谢谢大家。 PSL,我按照你的建议做了,现在它正在工作。就像你说的,我给和 id 并使用 getElementById,非常感谢你的提示。
猜你喜欢
  • 1970-01-01
  • 2014-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-24
  • 1970-01-01
  • 2011-08-12
相关资源
最近更新 更多