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/