将对象的值附加到特定的span元素

时间:2019-04-12 17:38:49

标签: javascript jquery

我正在从后端发送价格清单。

赞:[70, 90, 100, 140, 200]

在div内,我还有<span>个元素,带有特定的小节:

<span class="price_50_units"></span>
<span class="price_100_units"></span>
<span class="price_200_units"></span>
<span class="price_300_units"></span>
<span class="price_500_units"></span>

我需要将这些元素附加到其特定范围。列表的第一个元素将始终与class="price_50_units"的范围相对应:

<span class="price_50_units">70</span> #should be the result for the first span.

第二个元素将始终与class="price_100_units"对应的跨度,依此类推。

<span class="price_100_units">90</span> #should be the result for the second span.

现在,我可以使用以下代码将span元素和列表中的值放在div中:

req.done(function (response) {
     $('#prices').empty();
     var prices = response.prices;
     var list = '';
     for (var j = 0; j < prices.length; j++) {
         list += "<span>" + prices[j] + "</span></br>";
         }
     $('#prices').html(list);

    });

此代码将使用列表中的值创建新的span元素。

但是如何定位html中已经存在的span元素?

我在考虑这样的事情,但是没有用:

 $('p').children('span .price_50_units').text(prices[1]);

2 个答案:

答案 0 :(得分:1)

如果响应的索引和跨度的索引是直接相关的,那么您可以在跨度上放置一个通用类,并仅基于索引来设置其文本。

var responseData = [70, 90, 100, 140, 200];

$('.price').text(function(index){
  return responseData[index];
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="price price_50_units"></span>
<span class="price price_100_units"></span>
<span class="price price_200_units"></span>
<span class="price price_300_units"></span>
<span class="price price_500_units"></span>

答案 1 :(得分:1)

如果您的跨度并非总是按顺序创建,那么也许:

// Your data
var respData = [70, 90, 100, 140, 200];
// Loop through
$.each(respData, function(index, value ) {
  // Check if element exists. PS change selector if needed
  if($('span.price_' + value + '_units').length) {
    // add the value to the span
    $('span.price_' + value + '_units').text(value);
  }
});