尝试在以下内容中添加“sup”标记。它有效,但它克隆了它看到的第一个价格,任何想法为什么?
<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>';
})
);
});
答案 0 :(得分:2)
它不起作用,因为您再次请求'.pricecolor'
的每个元素。使用.html()
获取其当前HTML将始终返回第一个元素的HTML。
你应该这样做:
$('span.priceis').html(function (i, oldhtml) {
return oldhtml.replace(/\.\d{1,2}/,
function(a){
return '<sup>' + a + '</sup>';
});
});
注意:请勿使用font
标记,不推荐使用此标记。您可以使用简单的span
代替或任何语义匹配的元素。
答案 1 :(得分:1)
这可能会被重构,但问题已经解决:
$(document).ready(function(){
$('font.pricecolor').each(function() {
$(this).html(
$(this).html().replace(/\.\d{1,2}/,
function(a){
return '<sup>' + a + '</sup>';
})
);
});
});
您需要在嵌套函数中再次指定this
而不是类。
答案 2 :(得分: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>';
}));
});
});
答案 3 :(得分:1)
我认为你错误地使用html()
作为迭代器。请尝试使用each()
。此外,在您的块中,您希望使用this
来引用当前元素。最后是你的正则表达式的一个小优化。
$(document).ready(function() {
$('font.pricecolor').each(function() {
elem = $(this);
elem.html(elem.html().replace(/(\.\d{1,2})/, '<sup>$1</sup>'));
});
});
中查看