Javascript if语句不会触发

时间:2012-07-05 22:02:35

标签: javascript html conditional-statements

我一直在构建这个网站,根据搜索参数运行API。我使用if语句来确定下拉值。但由于某种原因,if语句没有运行。我有什么问题吗?这是代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript"></script>
<title>Testing</title>
</head>
<body>
<form name="bestbuysearch">
<select name="selection" onchange="setvalue()">
<option value="default">Select Category(Optional)</option>
<option value="abcat0100000">TV & Home Theater</option>
<option value="abcat0207000">Musical Instruments</option>
<option value="abcat0300000">Car, Marine & GPS</option>
<option value="abcat0400000">Cameras & Camcorders</option>
<option value="abcat0500000">Computers & Tablets</option>
<option value="abcat0600000">Movies & Music</option>
<option value="abcat0700000">Video Games</option>
<option value="abcat0800000">Mobile Phones</option>
<option value="abcat0900000">Appliances</option>
<option value="pcmcat142300050026">Outlet Center</option>
<option value="pcmcat242800050021">Health, Fitness & Sports</option>
<option value="pcmcat245100050028">Office</option>
<option value="pcmcat248700050021">Home</option>

</select>
<input type='text' id="item" placeholder='Search Here!' style='margin-top: 10px' size="70" maxlength=150 width="100px" />       
<input type='submit' value="Search" onclick="getstring(document.getElementById('item').value)"/> 
</form>


<script>
function setvalue(){
dropval=document.getElementsByName("selection")[0];
maindropval=dropval.value;
} 
function getstring(x){
    //link="http://api.remix.bestbuy.com/v1/products(name="+x+"*)?show=sku,name,regularPrice&apiKey=ydpyq9h9cmpmzaakbawv9mzk";
    //link2= "http://api.remix.bestbuy.com/v1/products(name=ipad|shortDescription=32gb*)?show=sku,name,shortDescription&apiKey=ydpyq9h9cmpmzaakbawv9mzk";
    link1="http://api.remix.bestbuy.com/v1/products(name="+x+"*)?show=sku,name,regularPrice,shortDescription&apiKey=ydpyq9h9cmpmzaakbawv9mzk";  
    link2="http://api.remix.bestbuy.com/v1/products(categoryPath.id="+maindropval+"&name="+x+"*)?show=sku,name,shortDescription,regularPrice,&apiKey=ydpyq9h9cmpmzaakbawv9mzk";
    if(maindropval=='default'){ 
    alert("worked");
        window.open(link1);}    
    else{
        window.open(link2);}


}
function getresult(value){
link="http://api.remix.bestbuy.com/v1/products(name="+x+"*)?show=sku,name,rating,regularPrice&apiKey=ydpyq9h9cmpmzaakbawv9mzk";
alert("step 2 completed");
}
</script>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

它不起作用的原因是变量maindropval仅在您更改下拉列表中的选择时设置。

要在变量中获取值"default",您必须选择下拉列表中第一项以外的内容,然后再次更改回第一项。

设置变量的初始值:

var maindropval = "default";

或在页面加载时运行该函数以设置值:

window.onload = setvalue;

(如果浏览器记住先前选择的表单值,则第二种解决方案是首选。在这种情况下,变量将根据记忆的下拉值设置。)

答案 1 :(得分:0)

迈克和我有同样的想法。

这是一个fiddle ...你的问题是maindropval的范围。