我有一个功能,当我在内部测试时工作但是,当我在家测试时它不起作用。该函数创建一个随机字符串,并在加载表单后立即调用它。我看起来除了功能之外一切正常。我不确定为什么会这样。有人可以帮助我吗?
感谢。
<script language="javascript" type="text/javascript">
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz";
var string_length = 3;
var randomstring = '';
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
document.getElementById('UniqueId').value = randomstring + hours + minutes + seconds;
}
</script>
答案 0 :(得分:0)
如果将此脚本放在head
标记内,则可能会在加载其余html之前执行该脚本。这意味着,没有加载id UniqueId
的元素,因此无法找到它。在html文档完全加载后尝试调用它。
yourFunction = function() { ...code... }
window.onload = yourFunction
<强>更新强>
<script type="text/javascript">
var randomString = function() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz";
var string_length = 3;
var randomstring = '';
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
document.getElementById('UniqueId').value = randomstring + hours + minutes + seconds;
}
window.onload = randomString;
</script>
在Windows XP和Chrome 21上测试Firefox 6和IE 8,在Mac OS X 10.8上测试Firefox 14。它有效。