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",
}
]
},
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键时,应该执行代码,如代码中所示。我是一名初学者,我正在努力寻找错误。
答案 0 :(得分:2)
searchInput=searchValue.value;
执行时将获得.value
的{{1}}属性,而不是创建指向它的指针。变量<input>
将只包含空字符串,并且不会更改。
将该分配移动到事件处理程序中,以便在单击按钮时检索该值,并且它将起作用。
(working demo at jsfiddle.net,也解决了@KevinBowersox提到的语法错误)
答案 1 :(得分: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。这些简单的语法错误很快就会被识别出来。