javascript - document.getElementById 破坏了代码

标签 javascript post methods getelementbyid

JavaScript

document.write(screen.width+'x'+screen.height);

var screenres='test';
document.write(screenres);
document.write('BBBBBBBBBBBBBBBBBBBBBBBBBBBB');

document.getElementById('resolutionfield').value = screenres;
document.write(screenres);
document.write('AAAAAAAAAAAAAAAAA');

我正在尝试获取用户屏幕分辨率并将其传递到 HTML post 方法中。如果我通过在前面添加两个斜杠来禁用 document.getElementById 行,此代码片段仅打印 1368x768testBBBBBBBBBBBBBBBBBBBBBBBBBBBB ,它会完美打印所有内容。

JavaScript

document.write(screen.width+'x'+screen.height);

var screenres='test';
document.write(screenres);
document.write('BBBBBBBBBBBBBBBBBBBBBBBBBBBB');

//document.getElementById('resolutionfield').value = screenres;
document.write(screenres);
document.write('AAAAAAAAAAAAAAAAA');

过去 4 个小时我一直在玩这个。这可能是一个简单的问题,但我就是无法弄清楚。

在我的代码中进一步

document.getElementById('secondsfield').value = seconds;
document.getElementById('minutesfield').value = minutes;
document.getElementById('hoursfield').value = hours;

这些变量可以毫无问题地传递到 post 方法中

HTML

<input type="hidden" id="usersipaddress" name="usersipaddress" value= "<?php echo $_SERVER['REMOTE_ADDR'];?>" >
<input type="hidden" id="secondsfield" name="secondsfield" value="" >
<input type="hidden" id="minutesfield" name="minutesfield" value="" >
<input type="hidden" id="hoursfield" name="hoursfield" value="" >
<input type="hidden" id="resolutionfield" name="resolutionfield" value="screenres" >

有人知道这个问题的答案吗?

最佳答案

如果这一行:

document.getElementById('resolutionfield').value = screenres;

在解析 resolutionfield DOM 元素并因此出现在 DOM 中之前执行得太早,那么这将导致错误并停止执行脚本。那是因为:

document.getElementById('resolutionfield')

将为null,然后当您尝试引用.value属性时,它将不起作用并会生成错误Uncaught TypeError:无法设置属性'value' of null 您可以在浏览器的错误控制台或调试控制台中看到它。

关于javascript - document.getElementById 破坏了代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21978876/

相关文章:

java - 无法发送多部分/表单数据

Django 表单 is_valid() 失败

java - java中如何使用参数和实参?

javascript - XML:通过值而不是属性来选择节点

javascript - ASP.NET Web 应用程序相对路径

javascript - 在不获取父项的情况下更新 Mongoose 中的子文档数组

javascript - 在 Windows 中预编译 Handlebars.js 模板

jQuery ajax POST 调用 - 不包括参数

java - 对于没有名称的弹出窗口,弹出窗口名称为 ="window"的 waitForPopUp 方法的奇怪行为?

C# 命名空间通信