2011-10-10 23 views
1

这是jQuery的:的Javascript更换不起作用

<script type="text/javascript"> 
    $(document).ready(function(){ 
     var relName; 
     $('.child').each(function() { 
      relName = $(this).attr('rel'); 
      relName.replace('&',''); 
      $(this).attr('rel', relName); 
      $(this).appendTo('#' + $(this).attr('rel')); 
     }); 
    }); 
</script> 

有了这个有关HTML:

<div rel="MadDogs&EnglishmenHandpaintedfigurines" id="Figurines" class="category section child"> 
    <h3 class="categoryTitle">Figurines</h3>    
</div> 

但由于某些原因,替换已经没有任何效果!

+0

我不知道这是否是你的整个问题,但'&'需要在HTML中为'&'。 – Brad

回答

8

replace返回带有替换数据的字符串。所以你需要分配回你的变量。

relName = relName.replace('&',''); 
+0

太棒了!我发誓我之前看过它写得不一样:S – benhowdle89

+0

@ benhowdle89:那么这段代码也是错误的;) –

3

replace()不改变原始字符串,它返回一个新的字符串。

+0

+1,因为这是正确的答案,但它会更好一个例子;) –

2

它没有更新,因为您没有将结果分配给任何东西。

试试这个:

$(this).attr('rel', relName.replace('&','')); 
2

下面就来写一个整洁的方式,使用的attr基本上每jQuery的方法callback version

$(document).ready(function() { 
    $('.child').attr('rel', function(i, relName) { 
     $(this).appendTo('#' + relName); 
     return relName.replace('&',''); 
    }); 
}); 
+0

非常整洁。 +1为一种新颖的解决方案。当你几乎说,jQuery的函数没有回调函数? – Bojangles

+0

@JamWaffles:我没有说“差不多”。 – Eric

+0

你说'基本'而不是。我只想知道哪些函数没有回调函数,或者是否有任何函数的列表。 – Bojangles