【发布时间】:2017-02-27 14:59:28
【问题描述】:
快速一:是否可以将元素的值替换为具有不同值的 SAME 类?
我的意思是:我有这个由 AJAX 响应返回的数组:
[
"$63.00 / Night",
"$68.00 / Night",
"$58.00 / Night",
"$50.00 / Night"
]
上面的数组是从一个看起来像这样的 html 响应生成的:
var result = [
"$63.00 / Night",
"$68.00 / Night",
"$58.00 / Night",
"$50.00 / Night"
];
console.log(result[0]);
result.forEach(function(item)
{
var num_price = parseFloat(item.replace( /[^\d\.]*/g, ''));
num_price = num_price * 2;
console.log(num_price);
$('.gdlr-tail').html(num_price);
});
<span class="gdlr-tail">$63.00 / Night</span>
<span class="gdlr-tail">$65.00 / Night</span>
<span class="gdlr-tail">$67.00 / Night</span>
<span class="gdlr-tail">$72.00 / Night</span>
从上面看,问题出现在代码的最后一行:$('.gdlr-tail').html(num_price);,它将我的.gdlr-tail 类中的所有值呈现为第一个跨度的值,即类中的所有值都已设置到126(63*2)。尽管我的数组在循环内,但会发生这种情况。仅计算第一个元素,所有其他元素都设置为此计算的值。
我哪里出错了?
【问题讨论】:
-
您也必须遍历
$('.gdlr-tail')。这就是为什么只更新第一个元素。我建议您使用for并使用索引来处理两个数组上的元素。
标签: javascript html arrays ajax