2014-11-05 168 views
1

我想要一个选择框来使用onchange函数来更新它周围的多个项目。这是我到目前为止的代码:选择框onchange更新多个项目

function picture() { 
var imglink; 
var imgprice; 
var picture_type = document.getElementById('picture_type').value; 
if ("picture_type" == "1") { 
    imglink = "img1.png"; 
    imgprice = "$xx.xx"; 
} 
if("picture_type" == "2") { 
    imglink = "img2.png"; 
    imgprice = "$xxx.xx"; 
} 
else { 
    document.getElementById('iphoneprice').style.display = 'none'; 
} 
document.getElementById('phoneimg').src = imglink; 
document.getElementById('iphoneprice').innerHTML = imgprice; 
} 

和匹配HTML:

<select id="picture_type" onchange="picture()"> 
<option value="1">iPhone 4</option> 
<option value="2">iPhone 4S</option> 
</select> 
<p id="iphoneprice"></p> 
<img id="iphoneimg" src="" /> 

我怎么能使其成功地同时更新这两个变量?

回答

0

你有一个错字(getElementById('phoneimg')应该是getElementById('iphoneimg'))和变量名称周围的引号。这应该工作:

function picture() { 
    var imglink; 
    var imgprice; 
    var picture_type = document.getElementById('picture_type').value; 
    if (picture_type == "1") { 
     imglink = "img1.png"; 
     imgprice = "$xx.xx"; 
    } 
    else if(picture_type == "2") { 
     imglink = "img2.png"; 
     imgprice = "$xxx.xx"; 
    } else { 
     document.getElementById('iphoneprice').style.display = 'none'; 
    } 
    document.getElementById('iphoneimg').src = imglink; 
    document.getElementById('iphoneprice').innerHTML = imgprice; 
} 

jsFiddle example

+1

谢谢!!完美地工作! – iDropNaughtCode 2014-11-05 22:11:27