我有一个函数,其中传入了一个参数sCellId
。我正在尝试使用获取其元素
var tdElement = document.getElementById(sCellId)
现在我在它后面进行了一个 null 检查,并且我完全希望它有时为 null
,这很好 (if (tdElement)
)。但是,似乎当传入空字符串时,我会得到一个异常:
Invalid procedure call or argument.
在 watch 中,如果我添加 document.getElementById("")
,它会正常工作并给我 null
。将 sCellId
添加到 watch ,我得到一个空字符串 ""
,如果我将 document.getElementById(sCellId)
添加到 watch ,它会再次出现显示错误。
这是所观察变量的快照:
我在这里缺少什么吗?
最佳答案
我也遇到了同样的问题,这似乎是 IE 中的一个错误,仅在使用 IE7 或 IE8 标准的兼容模式下才会出现。我能够使用下面的测试 HTML 页面在 IE 9 和 IE 11 中重现。如果我不启用兼容模式,则页面加载时不会出现任何错误。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<script type="text/javascript">
function runTest(ElementId) {
document.getElementById(ElementId);
}
window.onload = function () {
var fieldID = document.getElementById('TestHiddenField').value;
//DEBUG OTUPUT: you can un-comment this for more detailed output
//console.info("fieldId value: \"" + fieldID + "\""); //outputs: ""
//console.info("typeof(fieldId): " + typeof (fieldID)); //shows correctly as string
//console.info('fieldId.length: ' + fieldID.length); //0 length, so empty string.
//if (fieldID == "") {
// console.info("fieldId value matches to empty string");
//}
runTest(fieldID); //SCRIPT5: Invalid procedure call or argument
}
</script>
</head>
<body>
This is a test.
<input type="hidden" value="" id="TestHiddenField" />
</body>
</html>
尽管上面的所有调试输出都显示变量 fieldID
在运行时设置为空字符串,但(兼容模式)修复涉及更改此行:
var fieldID = document.getElementById('TestHiddenField').value;
将空字符串附加到隐藏字段值似乎可以修复错误:
var fieldID = document.getElementById('TestHiddenField').value + '';
奇怪的是,如果你将其更改为使用 .toString()
函数,那么它不起作用,并且仍然会收到错误:
var fieldID = document.getElementById('TestHiddenField').value.toString();
关于javascript - JS getElementById 带有空字符串 : Invalid procedure call or argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13178047/