美元符号Javascript字符串

时间:2012-02-04 20:57:10

标签: javascript string

我想解析一个元素并按货币设置区域。

HTML:

<span id="price">¥82,84</span><br/>

使用Javascript:

        price = document.getElementById("price").innerHTML;
        price = price.slice(0,1);

        if(price == "€")
        {
            area = "europe";
        }
        if(price == "£")
        {
            area = "europe";
        }
        if(price == "\$")
        {
            area == "northamerica";
        }
        if(price == "\¥")
        {
            area == "asia";
        }

欧元和英镑正在发挥作用,但日元和美元没有。有没有人有想法?

3 个答案:

答案 0 :(得分:9)

您在应使用赋值运算符==的语句中使用了等式比较=

答案 1 :(得分:7)

.innerHTML可能会返回HTML实体&dollar;。请改用.textContent.innerText。此外,由于price不能是两个不同的字符,我建议使用嵌套的else if而不是多个if

错误本身位于美元和人民币块:您使用==而不是普通=

    price = document.getElementById("price").textContent; // or innerText for IE
    price = price.charAt(0); // equal to .slice(0,1);

    if(price == "€") {
        area = "europe";
    } else if(price == "£") {
        area = "europe";
    } else if(price == "$") {
        area = "northamerica";
    } else if(price == "¥") {
        area = "asia";
    } else { // Default
        area = "Unknown";
    }

还有另外两种方法:

  • 切换块:

    switch(price) {
       case '€': case '£':
           area = 'europe';
       break;
       case '$':
           area = 'northamerica';
       break;
       case '¥'
           area = 'asia';
       break;
       default:
           area = 'unknown';
    }
    
  • 哈希:

    var price = document.getElementById("price").textContent; //or innerText (IE)
    price = price.charAt(0);
    var priceToArea = {
         '€': 'europe',
         '£': 'europe',
         '$': 'northamerica',
         '¥': 'asia'
    };
    var area = priceToArea[price] || 'Unknown'; //Default Unknown
    

答案 2 :(得分:2)

Rob W's answer之外,为清晰起见,我还会使用switch语句:

switch (price)
{
    case "€":
    case "£":
        area = "europe";
        break;
    case "$":
        area = "northamerica";
        break;
    case "¥":
        area = "asia";
        break;
}