在我的代码中找不到错误?

时间:2013-07-24 20:49:25

标签: javascript json search-engine

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

不要看按钮,我还没有添加事件监听器。 我只想在按下输入时显示产品。

HTML CODE

<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

3 个答案:

答案 0 :(得分: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删除了他们的答案,即删除第二个变量)。

答案 1 :(得分:1)

更改此

var list = {
   ...
},

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

到此:

var list = {
 ...
};

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

答案 2 :(得分:0)

在脚本结尾处还有一个逗号,在}

之后