javascript - document.getElementById() 始终返回 null

标签 javascript getelementbyid

我正在尝试使用 JavaScript 从 HTML 中的表单获取隐藏输入的值。 但是在尝试了几种不同的方法来获取值之后,它总是在控制台(firebug)中说该变量为空..这里是 javascript:

var mcq_test = form.mcq_test.value;
console.log("mcqid=" + mcq_test)
var mcq_num_questions = form.mcq_num_questions.value;
console.log("totalquestions=" + mcq_num_questions)
var x = 1;
var send = [];
send.push("mcq_test=");
send.push(mcq_test);

console.log("Send: " + send);

// have commented out the bits below...just go through them carefully looking at the string functions, put them in the send += (SRING 1 + STRING 2 + ...) format

for (var x = 1; x <= mcq_num_questions; x++) {
var questionidd = "mcq_question_id";
console.log("1 = " + questionidd);
var questionid = questionidd.concat(x); // mcq_question_id$ctr the question numer
console.log("2 = " + questionid);
var mcqid = form.questionid.value; // the questions id on db
console.log("3 = " + mcqid);
var answerr = "mcq_question";
var answer = answerr.concat(x); // mcq_question$ctr the questions chosen answer
var chosenanswer = form.answer.value; // the answers value
console.log("4 = " + chosenanswer);
var amp = "&";
var equal = "=";
var questionide = questionid.concat(equal); // "mcq_question_id$ctr="
var questionida = amp.concat(questionide); // "&mcq_question_id$ctr="
var answere = amp.concat(answer,equal); // "&mcq_question$ctr="
if (x = 1) { send.push(questionide, mcqid, answere, chosenanswer); }
else {
send.push(questionida, mcqid, answere, chosenanswer);
}
} 

控制台:

[04:08:00.328] TypeError: questionID is null 
[04:08:00.327] My new function
[04:08:00.327] mcqid=566
[04:08:00.327] totalquestions=3
[04:08:00.327] Send: mcq_test=,566
[04:08:00.328] 1 = mcq_question_id
[04:08:00.328] 2 = mcq_question_id1

表格:

echo"<input type=\"hidden\" name=\"mcq_question_id$ctr\" id=\"mcq_question_id$ctr\" value=\"$questionID\" form=\"SubmitTest\" />";

--更新

找到答案了!事实证明,您不能使用语法 document.getElementByID() 或 form.variable.value;并在其中放置一个变量,它必须是一个字符串或这样写:

form[variable].value;

我没有找到 getElementById 的等效项,但 form 方法对我有用。

最佳答案

在尝试访问 DOM 之前,您需要确保 DOM 已加载。将 Javascript 放在 HTML 后面或设置一个事件来触发变量定义。

关于javascript - document.getElementById() 始终返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14078655/

相关文章:

javascript - 使用 JS/jQuery 将行动态添加到表中时行消失

javascript - 使用数组匹配正则表达式

Javascript 一次获取多个 id

javascript - 为什么 `document.getElementById(“#datepicker1” )` 找不到我的元素?

javascript - 错误 : Uncaught TypeError: Cannot set property 'innerHTML' of null

javascript - ASP.NET MVC/Javascript : VideoJS media could not be loaded

javascript - 将 "this"替换为实际值

javascript - SilverStripe 前端 Ajax 博客文章使用 'read more' 按钮加载

javascript - 从另一个页面获取 ElementById

javascript问题getElementById修改CSS