2013-07-24 42 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