【问题标题】:jQuery loop through list-item and check child valuejQuery循环遍历列表项并检查子值
【发布时间】:2014-08-23 08:04:41
【问题描述】:

我正在尝试遍历一些列表项并检查子字段“.price”的值。 这是我正在使用的代码。

var item = jQuery(".product_overview li")

jQuery(item).each(function() {
var itemPrice = jQuery(".product_overview li .price").html();
alert(itemPrice);  
});

但是每个循环都给了我第一个孩子的价值..

HTML

<ul class="product_overview">
<li><span class="price">20</span></li>
<li><span class="price">40</span></li>
<li><span class="price">60</span></li>
</ul>

【问题讨论】:

  • 旁注:你不需要从item构造另一个jQuery对象,因为它已经是一个:item.each(function() { ...

标签: jquery list loops each


【解决方案1】:

如果你想要一个数组中的所有价格,

var prices = $.map($('.product_overview li'), function(){
    return this.querySelector('.price').innerHTML;
});

【讨论】:

    【解决方案2】:

    将您的代码更改为:

    var item = jQuery(".product_overview li")
    jQuery(item).each(function() {
        var itemPrice = jQuery(this).find(".price").html();
        alert(itemPrice);  
    });
    

    或者只是将整个内容重写为:

    jQuery(".product_overview li .price").each(function () {
        console.log(jQuery(this).html());
    });
    

    jsFiddle example

    【讨论】:

      【解决方案3】:

      尝试使用this 引用作为该选择器的context

      jQuery(item).each(function() {
        var itemPrice = jQuery(".price",this).html();
        alert(itemPrice);  
      });
      

      DEMO

      作为特殊情况,您在 UL 元素 clas="product_overview" 的 class 属性中错过了一个 s,请尝试在您的代码中更正它。

      【讨论】:

      • 谢谢,似乎可以在我缩短的演示代码中使用。实际目标是在 .price 元素上附加一个额外的类,基于它的值。如果值为“€0,00”,则为 .class1,否则为 .class2。我怎样才能做到这一点?以为我会通过提醒价值到达那里。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多