Javascript 字符串中的美元符号
我想解析一个元素并按货币设置区域。
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";
}
欧元和英镑有效,但日元和美元无效。有人有想法吗?
I want to parse an an element and set the area by currency.
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";
}
Euro and Pounds are working, but Yen and Dollar not. Does anyone have an idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您在应使用赋值运算符
=
的语句中使用了相等比较==
。You are using equality comparison
==
in the statements where you should use assignment operator=
..innerHTML
可能会返回 HTML 实体$
。请改用.textContent
或.innerText
。另外,由于price
不能是两个不同的字符,因此我建议使用嵌套的else if
而不是多个if
。错误本身位于美元和人民币区块:您使用的是
==
而不是普通的=
。还有另外两种方法:
切换块:
哈希:
: '北美', '¥': '亚洲' }; var 区域 = PriceToArea[价格] || '未知'; //默认未知
.innerHTML
might return the HTML entities$
. Use.textContent
or.innerText
instead. Also, sinceprice
cannot be two different chars, I suggest to use nestedelse if
s instead of multipleif
s.The error itself is located at the dollar and yuan blocks: You are using
==
instead of a plain=
.There are two other methods:
Switch blocks:
Hashes:
: 'northamerica', '¥': 'asia' }; var area = priceToArea[price] || 'Unknown'; //Default Unknown
: area = 'northamerica'; break; case '¥' area = 'asia'; break; default: area = 'unknown'; }: area = 'northamerica'; break; case '¥' area = 'asia'; break; default: area = 'unknown'; }
Hashes:
Hashes:
除了 Rob W 的回答之外,为了清楚起见,我还将使用 switch 语句:
Further to Rob W's answer I would also use a switch statement for clarity: