-5

代码

<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代码

(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",
  }
  ]
},

 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

我需要有人帮助我编写代码。我不知道为什么它不起作用。这是一个简单的搜索框。不注意按钮。正如您在代码中看到的那样,当我按 Enter 时应该执行代码。我是一个初学者,我尝试了几个小时来找出我的错误。

4

2 回答 2

2
searchInput=searchValue.value;

这将获得执行时的.value属性<input>,而不是创建指向它的指针。该变量searchInput将只包含空字符串,并且不会改变。

将该分配移动到事件处理程序中以在单击按钮时检索值,它将起作用。

在 jsfiddle.net 工作演示,还修复了@KevinBowersox 提到的语法错误)

于 2013-07-25T00:44:29.890 回答
0

这个对象字面量不会飞入IE你在属性列表末尾有额外的逗号。

var list= {

  "listOfProducts": [

  {
  "name":"hard disk",
  "price": "50$",
  "quality":"good", <-- remove these since there is no property after
  },
  {
  "name":"monitor",
  "price":"100$",
  "quality": "very good", <-- remove these since there is no property after
  },
  //rest of object omitted, still needs changed...
}; <-- end with semicolon

匿名函数(我假设自己执行?)也没有正确关闭。

(function(){
  //code goes in here

})(); <--- This piece is missing;

我会推荐一个好的 Javascript 编辑器,比如 Aptana。这些简单的语法错误会很快被识别出来。

于 2013-07-25T00:34:31.207 回答