0

我正在制作一个简单的搜索代码。我找不到错误。错误消息说Uncaught SyntaxError: Unexpected identifier on javascript line 40 (target=document.getElementById("outputPlace")

不要看按钮,我还没有给它添加事件监听器。我只希望当我按 Enter 时显示产品。

代码

<html>
<head>

<title>Price List </title>

</head>

<body>

<h1> PRICELIST </h1>
<form id="formSearch">
<div>
<label for="searchBox"> Search products here: </label>
<input type="text" placeholder="Type text here to search product" id="searchBox">
</div>
<div id="buttons">
<button id="getAll"> GET ALL PRODUCTS</button>
</div>

</form>

<div id="outputPlace">

</div>


<script src="product.js"></script>
</body>


</html>


JAVASCRIPT CODE

(function(){                    //start anonymous function

var list= {

  "listOfProducts": [

  {
  "name":"hard disk",
  "price": "50$",
  "quality":"good",
  },
  {
  "name":"monitor",
  "price":"100$",
  "quality": "very good",
  },
  {
  "name":"speakers",
  "price":"20$",
  "quality": "not bad",
  },
  {
  "name":"headphones",
  "price":"12$",
  "quality":"bad",
  },
  {
  "name": "mobile phone",
  "price": "300$",
  "quality": "excellent",
  },
  {
  "name": "usb memory",
  "price": "30$",
  "quality": "the best",
  }
  ]
},

var target=document.getElementById("outputPlace"),
    searchForm=document.getElementById("formSearch"),
    productList=list.listOfProducts,
    listLength=productList.length,
    searchValue=document.getElementById("searchBox"),
    searchInput=searchValue.value;




var listMethods = {

searchList: function(event) {

event.preventDefault();
var i;
target.innerHTML="";
if(listLength>0 && searchInput!=="") {

   for(i=0;i<listLength;i++) {
   var product=productList[i],
       whatIsFound=product.name.indexOf(searchInput);
       if(whatIsFound!==-1){

       target.innerHTML+='<p>'+product.name+', '+product.price+', '+product.quality+'<a href="http//www.facebook.com">click here to buy</a></p>'
       }

   }


}





},





};

searchForm.addEventListener("submit",listMethods.searchList,false);








}) (); //end anonymous function
4

3 回答 3

2

在 JavaScript 顶部定义的大型 JSON 对象后面有一个逗号,然后是另一个 var。

var list= {
 "listOfProducts": [
 {
  "name":"hard disk",
  "price": "50$",
  "quality":"good",
 },
 ...[a bunch of stuff]...
},

var target=document.getElementById("outputPlace"),
    searchForm=document.getElementById("formSearch"),
    productList=list.listOfProducts,
    listLength=productList.length,
    searchValue=document.getElementById("searchBox"),
    searchInput=searchValue.value;

其他两个提议的答案都可以解决这个问题(好吧,Otome 删除了他们的答案,即删除第二个 var)。

于 2013-07-24T20:51:47.013 回答
1

改变这个

var list = {
   ...
},

var target=document.getElementById("outputPlace"),

对此:

var list = {
 ...
};

var target=document.getElementById("outputPlace"),
于 2013-07-24T20:53:10.670 回答
0

在 } 之后,脚本末尾还有一个逗号

于 2013-07-24T20:56:34.370 回答