2011-05-12 60 views
0

試圖添加一個'sup'標籤到下面。它的工作原理是克隆它看到的第一個價格,爲什麼?jQuery替換是克隆,我需要它爲每個元素

<font class="pricecolor colors_productprice specialprice"> 
    <span class="PageText_L483n"> 
    <font class="text colors_text"><b>Regular Price:</b></font> 
    <span class="priceis strike">$2,533.31</span> </span> 
</font> 

<font class="pricecolor colors_productprice specialprice"> 
    <span class="PageText_L483n"> 
    <font class="text colors_text"><b>Regular Price:</b></font> 
    <span class="priceis strike">$288.00</span> </span> 
</font> 

<font class="pricecolor colors_productprice specialprice"> 
    <span class="PageText_L483n"> 
    <font class="text colors_text"><b>Regular Price:</b></font> 
    <span class="priceis strike">$1,055.00</span> </span> 
</font> 

$(document).ready(function(){ 
    $('font.pricecolor').html(
     $('.pricecolor').html().replace(/\.\d{1,2}/, 
      function(a){ 
       return '<sup>' + a + '</sup>'; 
      }) 
    ); 
}); 
+2

*喘氣* FONT標籤! – mattsven 2011-05-12 18:30:29

+0

我使用Volusion^O.o – ToddN 2011-05-12 18:33:35

回答

1

我認爲你錯誤地使用了html()作爲迭代器。改爲嘗試each()。此外,在你的塊中,你希望使用this來引用當前元素。最後爲你的正則表達式做一個小的優化。

$(document).ready(function() { 
    $('font.pricecolor').each(function() { 
     elem = $(this); 
     elem.html(elem.html().replace(/(\.\d{1,2})/, '<sup>$1</sup>')); 
    }); 
}); 

看到它在行動http://jsfiddle.net/teXCc/

+0

這工作完美,非常感謝你 – ToddN 2011-05-12 18:40:41

2

它不會對每一個我們再次請求'.pricecolor'元素,因爲工作。使用其上的.html()來獲取其當前HTML將始終返回第一個元素的HTML。

你應該做這樣的事情:

$('span.priceis').html(function (i, oldhtml) { 
    return oldhtml.replace(/\.\d{1,2}/, 
      function(a){ 
       return '<sup>' + a + '</sup>'; 
      }); 
}); 

jsFiddle Demo

注:不要使用font標籤,它已經過時了。您可以使用簡單的span,或使用任何語義匹配的元素。

+1

我沒有意識到'.html'可以接受一個函數。 +1 :) – Jeff 2011-05-12 18:43:00

+0

+1 @Jeff說的。 – 2011-05-12 18:46:57

1

這也許可以重構,但問題得到解決:

$(document).ready(function(){ 

    $('font.pricecolor').each(function() { 
     $(this).html(
      $(this).html().replace(/\.\d{1,2}/, 
       function(a){ 
        return '<sup>' + a + '</sup>'; 
       }) 
     ); 
    }); 

}); 

您需要在您的嵌套函數再次指定this,而不是類。

1

我覺得這裏有一些小小的誤解。選擇器font.pricecolor將選擇您正在查找的所有字體標籤。但是,當您使用.html(value)設置HTML對象的列表時,僅爲列表中的第一個項目計算value,該值將重新用於列表的其餘部分。

您需要使用.each才能爲列表中的每個項目創建一個新值。試試這個...

$(document).ready(function() 
{ 
    $('font.pricecolor').each(function(i) 
    { 
     var $this = $(this); 
     $this.html($this.html().replace(/\.\d{1,2}/, 
      function(a) 
      { 
       return '<sup>' + a + '</sup>'; 
      })); 
    }); 
});