I'm having a problem where a jQuery setting against an .html() property on a selected element is returning the error 'nodeName' is null or not an object. This only occurs on IE6 and IE7, but not FF2, FF3, Opera (latest Nov 12,2008) or Safari (again, latest).
5 回答
I resolved the problem. The example looks like this:
$('#section #detail .data').html(data);
...where data is HTML returned from an AJAX call, and this bug only occurs on IE6 and IE7 on the second attempt AJAX call, not the first. It's inexplicable. The error returned is:
'nodeName' is null or not an object
The fix is to simply clear the variable first before setting:
$('#section #detail .data').html(''); $('#section #detail .data').html(data);
And then IE6 and IE7 started working again with it.
BTW, I had to install Visual Web Developer 2008 Express Edition to get a debugger working in IE7. That info is here.
在我看来,它就像 JQuery 中的一个错误。在 1.5.1 的第 605 行抛出异常:
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
},
如果 object 的 nodeNameelem
与 String 相同,则该函数返回 true name
。如果不是,或者如果没有 nodeName at elem
,我们返回 false。但是,elem
在使用之前没有经过测试。所以如果elem
为null,调用它的.nodeName
成员就会抛出一个空指针异常。
一个简单的解决方法是elem
在短路AND子句的开头包含:
return elem && elem.nodeName && elem.nodeName.toUpperCase()...
现在如果elem
为 null,该函数将在子句中的第一次测试时返回 false 并且永远不会尝试调用elem.nodeName
,从而避免了 NPE。
我没有全部检查(它被大量使用),但在许多使用此函数的情况下,在函数调用之前进行了测试elem
。但显然,并非在所有情况下。
对我来说,当我试图选择一个不存在的元素时,它发生在 IE 上。我试图在它的兄弟姐妹中获取它的索引,它返回为-1。然后我尝试通过从其父级获取它的索引来显示这个元素。它导致了这个错误。
因此,我检查了索引是否不等于-1。这为我解决了这个问题。
I don't know if it's connected, but we've had what sounds like a similar issue where the DOM doesn't have the children/text of a element that we know exist (because we see them rendered on the screen!)
Selecting something else, then selecting the elememt again seemed to fix the issue - suddenly, the children appear. So what happens if you select you element, select something else, select your element again?
Do you have any idea what kinds of nodes you might be running up against? Or, are you running in IE quirks mode? There might be some kinds of nodes such as #text that don't show up correctly in the DOM in quirks mode.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">