Javascript更改图标

Javascript change icon

本文关键字:图标 Javascript      更新时间:2023-09-26

我尝试用select元素更改图标。我已经用了2个值,但现在我需要3个。

知道这个代码出了什么问题吗?

var icon = document.getElementById.("marker-icon"); 
    if (type == 1) {  
        marker-icon.src = "images/icon1.png";
    } else if (type == 2) {
        marker-icon.src = "images/icon2.png";
    } else if (type == 3) {
        marker-icon.src = "images/icon3.png";
}

此代码适用于2个值,并且运行良好。

var icon = (type == 1) ? "images/icon1.png" : "images/icon2.png";

试试这个:

var icon = document.getElementById("marker-icon"); 
if (type == 1) {  
    icon.src = "images/icon1.png";
} else if (type == 2) {
    icon.src = "images/icon2.png";
} else if (type == 3) {
    icon.src = "images/icon3.png";
}

getElementById之后有一个额外的.,您使用的是marker-icon而不是icon。(我假设marker-iconimg标签的id。)

尝试使用切换大小写语法。

switch (type) {
    case 1:
        var icon =  "images/icon1.png";
        break;
    case 2:
        var icon =  "images/icon2.png";
        break;
    case 3:
        var icon =  "images/icon3.png";
        break;
    default:
        //default code block
        break;
}

它适用于:

var icon = document.getElementById("icon"); 
    if (type == 1) {  
        icon = "images/icon1.png";
    } else if (type == 2) {
        icon = "images/icon2.png";
    } else if (type == 3) {
        icon = "images/icon3.png";
    }

谢谢大家!^^