2013-07-24 43 views
0

我试图循环遍历所有价格跨度,然后插入一些显示其储蓄的HTML。.next()在每个循环中未定义

只要我删除.each功能和(this).next,我可以得到这个工作在一个产品上就好了。

我在Firebug得到的错误是TypeError: jQuery(...).next(...).html(...) is undefined

jQuery('.price').each(function(){ 

    var pricea = parseInt(jQuery(this).next(".count .amount:first").html().replace("£","")) ; 
    var priceb = parseInt(jQuery(this).next(".count .amount:last").html().replace("£","")); 
    var total = (pricea - priceb)/(pricea) * 100; 
    var totalfixed = total.toFixed(); 
    jQuery(this).next('.saving').append(totalfixed); 

    console.log(totalfixed); 

}); 

我的HTML:

<li class="product "> 
    <span class="price"> 
    <del class="count"><span class="amount2">WAS</span><span class="amount">&pound;35</span></del> 
    <ins class="count"><span class="amount2">NOW </span><span class="amount">&pound;20</span><span style="clear:both" class="saving"> <br><br> YOU SAVE %</span></ins> </span> 
</li> 

<li class="product "> 
    <span class="price"> 
    <del class="count"><span class="amount2">WAS</span><span class="amount">&pound;35</span></del> 
    <ins class="count"><span class="amount2">NOW </span><span class="amount">&pound;20</span><span style="clear:both" class="saving"> <br><br> YOU SAVE %</span></ins> </span> 
</li> 

您可以查看现场演示Here

+0

当我把上述代码放在[this jsfiddle](http://jsfiddle.net/biinjo/R4rjx/)中时,我得到了一个不同的错误:未捕获TypeError:无法调用未定义的方法'replace'。 你使用的是什么jQuery版本? –

回答

1

当我把上面的代码中this jsfiddle我得到一个不同的错误:

Uncaught TypeError: Cannot call method 'replace' of undefined.

这虽然解决您的问题:

jQuery('.price').each(function(){ 

    var pricea = parseInt(jQuery(this).find(".amount:first").html().replace("£","")) ; 
    var priceb = parseInt(jQuery(this).find(".amount:last").html().replace("£","")); 

    var total = (pricea - priceb)/(pricea) * 100; 

    jQuery(this).next('.saving').append(total.toFixed()); 

}); 

.find()搜索里面jQuery(this).amount类的元素( :第一个和最后一个)

1

。接下来( '节省')期待找到类似于.price旁边的节省类别的跨度代码,如下所示:

<span class="price"></span> 
<span class="saving"></span> // <-- it is looking for this 

但你的代码是这样的:

<span class="price"> 
    <span class="saving"></span> 
</span> 

您的具体情况,你需要

jQuery(this).find('.saving').append(totalfixed); //this will find .saving inside of .price 

为了记录我只能看到这一次,我把HTML在我的编辑器突出显示打开/关闭标签。请格式化您的代码不仅适合我们,而且适合您自己,它会为您节省不少麻烦。

+0

谢谢!抱歉必须忽视那个愚蠢的我 – Brent