Javascript - 用不同的值替换具有相同类的元素

时间:2016-10-18 11:03:37

标签: javascript html arrays ajax

快速一:是否可以使用不同的值替换 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>
&#13;
&#13;
&#13;

从上面开始,麻烦在代码的最后一行开始:$('.gdlr-tail').html(num_price);,它将我.gdlr-tail类中的所有值都渲染为第一个范围的值,即所有值该类设置为126(63*2)。虽然我的数组在循环中,但会发生这种情况。仅计算第一个元素,并将所有其他元素设置为此计算的值。

我哪里可能出错?

3 个答案:

答案 0 :(得分:1)

迭代new元素,而不是价格。然后为每个元素分配数组中的相应值:

.gdlr-tail
var result = [
  "$63.00 / Night",
  "$68.00 / Night",
  "$58.00 / Night",
  "$50.00 / Night"
];

$('.gdlr-tail').each(function(index, el)
{
    var num_price = parseFloat(result[index].replace( /[^\d\.]*/g, ''));
    num_price = num_price * 2;

    $(el).html(num_price);
});

答案 1 :(得分:1)

确实如此,但为了理智,最好先将它们分组,以避免在页面的其他地方进行不必要的更改:

&#13;
&#13;
var result = [
  "$63.00 / Night",
  "$68.00 / Night",
  "$58.00 / Night",
  "$50.00 / Night"
];

result.forEach(function(item, index) {

  var num_price = parseFloat(item.replace(/[^\d\.]*/g, ''));
  num_price = num_price * 2;
  console.log(num_price);

  $('.gdlr-tail-parent .gdlr-tail:nth-child(' + (index + 1) + ')').html(num_price);

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gdlr-tail-parent">
  <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>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

我认为你的事情是这样的 - &gt;

重新格式化。 ?

var result = [
  "$63.00 / Night",
  "$68.00 / Night",
  "$58.00 / Night",
  "$50.00 / Night"
];

var tails = $('.gdlr-tail');
result.forEach(function(item, index)
{
  var num_price = parseFloat(item.replace( /[^\d\.]*/g, ''));
  num_price = num_price * 2;  
  $(tails[index]).text("$" + num_price.toFixed(2) + " / Night");  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>