我是JavaScript和HTML的新手,对基本问题感到抱歉。基本上我有这个HTML文件应该在加载时运行我的文件script.js,我的朋友告诉我使用$(function(){)来包含代码所以当我加载页面时它会运行整个脚本。但是,当我运行脚本时,没有任何事情发生,创建网页应该在一个对象数组加载到数组问题后在div id = question_text中设置文本。
以下是我的HTML主管,您可以看到我在script.js中添加了
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../css/bootstrap-theme.min.css">
<link rel="stylesheet" href="../css/bootstrap.min.css">
<script src="../js/script.js"></script>
<title>Patient Questionnaire</title>
</html>
这是我的JavaScript
$(function() {
questions = [];
count = 0;
addQuestions();
createWebpage();
function Question(questionText, possibleAnswers, chosenAnswer) {
this.questionText = questionText;
this.possibleAnswers = possibleAnswers;
this.chosenAnswer = chosenAnswer;
}
function addQuestions() {
var question1 = new Question(
"Do you have or have you ever had high blood pressure?", ['Yes', 'No'],
""
);
var question2 = new Question(
"Within the last year, have you had chest pain or pressure with activity such as walking or climbing stairs?", ['Yes', 'No'],
""
);
var question3 = new Question(
"Do you currently take medication to prevent or reduce agnia (chest pain from the heart)?", ['Yes', 'No'],
""
);
var question4 = new Question(
"Have you ever had a heart attack?" ['Yes', 'No'],
""
);
questions.push(question1);
questions.push(question2);
questions.push(question3);
questions.push(question4);
}
function createWebpage() {
document.getElementById("question_text").innerHTML = questions[1].questionText;
console.log("questions")
}
});
我之前只使用过几次JavaScript,但通常我已经能够通过获取elementID并将其设置为我想要的来实现它。
非常感谢任何帮助!
答案 0 :(得分:1)
您必须使用以下语法才能执行Javascript代码:
(function(){
...
})();
这是一个工作小提琴:http://jsfiddle.net/470sk1gd/
在我看来,在这种情况下不需要使用jQuery。
答案 1 :(得分:0)
将alert('Start');
放在JavaScript文件的第一行,看看它是否完全加载。
正如SLaks所说,要使$
起作用,你需要jQuery。所以你也需要加载它。