【问题标题】:Jquery - Using .each() with variables and an IF statementJquery - 将 .each() 与变量和 IF 语句一起使用
【发布时间】:2012-07-01 23:51:31
【问题描述】:

现在花了好几个小时,但似乎没有任何进展!

我在页面底部有 5 个相关产品。目前,无论是否打折,这些产品都会显示“原价”。上面是实际价格,显然如果产品不打折,价格看起来会一样,这并不酷。

所以我编写了一个脚本来检查“实际”价格是否与“原价”价格相同,如果为真,它会简单地删除“原价”Div 元素。工作正常。

现在我遇到的问题是使此规则适用于页面中具有相同类的多个元素。出于某种原因,当我尝试在“.each”函数中传递一个变量时,它返回一个字符串,其中包含每个“.each”元素的所有 Div 值,而不是只返回其相对父元素的值。例如“£674£1999.99£674”而不是“£674”。

检查实际价格是否与原来的价格相同:

    $('.floatleft').each(function() {
    var wasprice = $('.was').text();
    var ourprice = $('.now').text();

    if (wasprice == ourprice) {

    $('div.price-extras').remove();
    $('.productdetails-view .product-price .PricesalesPrice').css('line-height','40px');

};
});

HTML 代码示例:

<div class="vmproduct-featured">
  <div class=" width20 floatleft">
    <div class="spacer">
      <a href="/store/powertools/tacx-i-magic-t1900-trainer-info" title="Tacx I-Magic T1900 Trainer" class="img-link">
        <img src="/store/product/resized/123_150x150.jpg" alt="123" class="featuredProductImage" border="0">
      </a>
      <div class="clear"></div>     
      <a class="text-link" href="/store/powertools/tacx-i-magic-t1900-trainer-info">Tacx I-Magic T1900 Trainer</a>      
      <div class="clear"></div>
      <div class="was">£674.00</div>
      <div class="now">£674.00</div> 
    </div>
  </div>
  <div class=" width20 floatleft">
    <div class="spacer">
      <a href="/store/powertools/2012-cube-agree-gtc-di2-info" title="2012 Cube Agree GTC DI2" class="img-link">
        <img src="/store/product/resized/12cubeagreegtcdi2_150x150.jpg" alt="12cubeagreegtcdi2" class="featuredProductImage" border="0">
      </a>
      <div class="clear"></div>     
      <a class="text-link" href="/store/powertools/2012-cube-agree-gtc-di2-info">2012 Cube Agree GTC DI2
      </a>      
      <div class="clear"></div>
      <div class="was">£1,999.99</div>
      <div class="now">£2,499.99</div> 
    </div>
  </div>
 </div>

所以基本上我在 .each() 上失败了,需要一些帮助,请

【问题讨论】:

    标签: jquery variables if-statement each


    【解决方案1】:

    那是因为$('.was').text(); 一次选择了was 类的所有文本,试试这个:

    $('.was').each(function() {
        var wasprice = $(this).text();
        var ourprice = $(this).siblings('.now').text(); // or "$(this).next('.now').text();"
    
        if (wasprice == ourprice) { 
            $('div.price-extras').remove();
            $('.productdetails-view .product-price .PricesalesPrice').css('line-height','40px');
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2015-01-15
      • 2018-07-31
      • 2015-09-05
      • 1970-01-01
      • 2011-06-09
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多