无法设置未定义或 null 引用的属性"innerText"

您所在的位置:网站首页 无法获取未定义或null引用的属性“text” 无法设置未定义或 null 引用的属性"innerText"

无法设置未定义或 null 引用的属性"innerText"

2024-07-17 04:04| 来源: 网络整理| 查看: 265

今天在测试的过程中,ie环境下一直在报“无法设置未定义或 null 引用的属性”value””,在网上也搜了很多结果,有的说是引用的jquery版本太高导致的,有的方法是加.get(0),但是这些方式我已经统统试过,至少在我的项目中没有起到任何作用。下面我将通过代码为大家进行讲解。

代码如下:

function scrollDoor(){ } scrollDoor.prototype = { sd : function(menus,divs,openClass,closeClass){ var _this = this; if(menus.length != divs.length) { alert("菜单层数量和内容层数量不一样!"); return false; } for(var i = 0 ; i < menus.length ; i++) { _this.$(menus[i]).value = i; _this.$(menus[i]).onclick = function(){ for(var j = 0 ; j < menus.length ; j++) { _this.$(menus[j]).className = closeClass; _this.$(divs[j]).style.display = "none"; } _this.$(menus[this.value]).className = openClass; _this.$(divs[this.value]).style.display = "block"; } } }, $ : function(oid){ if(typeof(oid) == "string") return document.getElementById(oid); return oid; }, } window.onload = function(){ var SDmodel = new scrollDoor(); SDmodel.sd(["m01","m02","m03","m04","m05"],["c01","c02","c03","c04","c05"],"sd01","sd02"); }

以上代码就是网上经常在使用的scrollDoor插件,在crome和Firefox中测试均无问题,但是我们调皮的ie问题就来了,各种报错,然而报的错都是‘无法设置未定义或null引起的某一属性’。充分证明插件是可以使用的,可是我们如何解决ie中的问题呢?

我仔细的研究了一下插件,发现报错原因是因为我们页面上不存在以数组["m01","m02","m03","m04","m05"]中某一属性为id的元素,即找不到id为”m01”/“m02”/”m03”/“m04”的元素,所以无法设置其属性。问题找到了,就好解决了,于是我对该插件进行了扩展,写了一个方法作为判断页面上是否有id为特定值的元素,如果有,执行方法,没有,结束。代码如下:

function scrollDoor(){ } scrollDoor.prototype = { sd : function(menus,divs,openClass,closeClass){ var _this = this; if(menus.length != divs.length) { alert("菜单层数量和内容层数量不一样!"); return false; } for(var i = 0 ; i < menus.length ; i++) { if(_this.exist(menus[i])) { //判断开始,注意调用的时候一定要加上_this _this.$(menus[i]).value = i; _this.$(menus[i]).onclick = function(){ for(var j = 0 ; j < menus.length ; j++) { _this.$(menus[j]).className = closeClass; _this.$(divs[j]).style.display = "none"; } _this.$(menus[this.value]).className = openClass; _this.$(divs[this.value]).style.display = "block"; } } } }, $ : function(oid){ if(typeof(oid) == "string") return document.getElementById(oid); return oid; }, exist:function(id){ //该方法为判断某id的元素是否存在 var s=document.getElementById(id); if(s){return true} else{return false} } } window.onload = function(){ var SDmodel = new scrollDoor(); SDmodel.sd(["m01","m02","m03","m04","m05"],["c01","c02","c03","c04","c05"],"sd01","sd02"); }

到此为止,就已经解决了该问题。曾经在其他情况下,也遇到过此问题,只是没有解决,其实都大同小异,找到为什么,解决就可以了。多说一句,很多人对代码中的var _this = this;举个例子:

$("#btn").click(function(){ var _this = this;//这里this和_this都代表了"#btn"这个对象 $(".tr").each(function(){ this;//在这里this代表的是每个遍历到的".tr"对象 _this;//仍代表"#btn"对象 }) })

这种情况就是在一个代码片段里this有可能代表不同的对象,而编码者希望_this代表最初的对象。

好啦,愉快的旅程到此结束!



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3