使用jquery更改列表框上的图像属性更改

时间:2016-08-17 15:28:33

标签: javascript jquery html listbox attributes

我想显示一个专辑库,可以从每个单独文件夹的选择框中选择。

下面的HTML代码:

<select name="album" id="album" onChange="changeimage();">
    <option value="0" selected disabled>Select an album gallery...</option>
    <option value="1">RC</option>
    <option value="2">MR</option>
    <option value="3">CD</option>
    <option value="4">KP</option>
    <option value="5">SH</option>
</select>

<!-- Display default images on page load -->
<img src="images/rC/img1.jpg" id="img1" title="RC" alt="Image1"/> 
<img src="images/rC/img2.jpg" id="img2" title="RC" alt="Image2"/> 
<img src="images/rC/img3.jpg" id="img3" title="RC" alt="Image3"/> 
<img src="images/rC/img4.jpg" id="img4" title="RC" alt="Image4"/> 
<img src="images/rC/img5.jpg" id="img5" title="RC" alt="Image5"/>

jQuery代码如下:

function changeimage() {
    "use strict";
    var folder;
    var img_title;

    if ($("select#album").val() === 1) { 
        folder = "rC/img"; img_title = "RC";
    } else if ($("select#album").val() === 2) {
        folder = "mR/img"; img_title = "MR";
    } else if ($("select#album").val() === 3) { 
        folder = "cD/img"; img_title = "CD";
    } else if ($("select#album").val() === 4) { 
        folder = "kP/img"; img_title = "KP";
    } else if ($("select#album").val() === 5) {
        folder = "sH/img"; img_title = "SH";
    }

    $("img#img1").attr({ src: "images/" + folder + "1.jpg", title: img_title, alt: "Image1" });
    $("img#img2").attr({ src: "images/" + folder + "2.jpg", title: img_title, alt: "Image2" });
    $("img#img3").attr({ src: "images/" + folder + "3.jpg", title: img_title, alt: "Image3" });
    $("img#img4").attr({ src: "images/" + folder + "4.jpg", title: img_title, alt: "Image4" });
    $("img#img5").attr({ src: "images/" + folder + "5.jpg", title: img_title, alt: "Image5" });
}

1 个答案:

答案 0 :(得分:0)

Jquery .val()返回value所选选项的string属性的内容。你的代码问题是有条件的。

if ($("select#album").val() === 1)

在if条件中使用===时,意味着值的类型应该相等。虽然1不等于"1"。你需要使用

if ($("select#album").val() === "1")
// or
if ($("select#album").val() == 1)