选择Box onchange更新多个项目

时间:2014-11-05 21:29:04

标签: javascript html variables

我正在尝试使用一个选择框来使用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="" />

如何让它同时成功更新这两个变量?

1 个答案:

答案 0 :(得分: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