在此代码中,单击“提交”按钮时,它不会显示警报消息。但是,当您删除对象和属性定义时,它可以正常工作。
<--!DOCTYPE html>
<html>
<head>
<title>This is just a test</title>
<script src="script.js"></script>
</head>
<body>
<h1>This is going to be the search bar</h1>
<form>
<input type="text" id="BookName" name="Book1">
<input type="submit" id="Searchbtn" onclick="algo()">
</form>
<script>
function algo(){
alert("It is working");
};
var search = document.getElementById("BookName");
var bookDirectory = {};
bookDirectory.book1 = {
bookName = "book1",
bookTag1 = "MAIT",
bookTag2 = "3rd Semester"
};
bookDirectory.book2 = {
bookName = "book2",
bookTag1 = "NIEC",
bookTag2 = "1st Semester"
};
bookDirectory.book3 = {
bookName = "book3",
bookTag1 = "USIT",
bookTag2 = "5th Semester"
};
</script>
<h2 id="Book1">This is going to be the book</h2>
</body>
</html>
为什么删除对象和属性定义会有效?:
<!DOCTYPE html>
<html>
<head>
<title>This is just a test</title>
<script src="script.js"></script>
</head>
<body>
<h1>This is going to be the search bar</h1>
<form>
<input type="text" id="BookName" name="Book1">
<input type="submit" id="Searchbtn" onclick="algo()">
</form>
<script>
function algo(){
alert("It is working");
};
</script>
<h2 id="Book1">This is going to be the book</h2>
</body>
</html>
答案 0 :(得分:3)
您错误地定义了Object Literals。
而不是在定义中使用=
:
bookDirectory.book1 = {
bookName = "book1",
bookTag1 = "MAIT",
bookTag2 = "3rd Semester"
};
你 应该用:
来定义它们,如下所示:
bookDirectory.book1 = {
bookName: "book1",
bookTag1: "MAIT",
bookTag2: "3rd Semester"
};
因为这些是使用不正确的语法定义的,所以整个<script>
块及其中的所有代码都无效且无法使用。
请注意,您可能用于测试的大多数浏览器都有一个可用于检查错误的开发控制台,这个错误的分配肯定会在您的控制台中显示。对于大多数浏览器,打开开发人员面板的默认键是 F12 。