Javascript替换没有任何效果
这是jQuery:
$(document).ready(function(){ var relName; $('.child').each(function() { relName = $(this).attr('rel'); relName.replace('&',''); $(this).attr('rel', relName); $(this).appendTo('#' + $(this).attr('rel')); }); });
使用这个相关的HTML:
Figurines
但由于某种原因,替换没有任何影响!
replace
返回带有替换数据的字符串。 所以你需要分配回你的变量。
relName = relName.replace('&','');
replace()
不会更改原始字符串,而是返回一个新字符串。
它没有更新,因为你没有将结果分配给任何东西。
试试这个:
$(this).attr('rel', relName.replace('&',''));
这是编写它的一种简洁方法,使用的回调版本基本上每个jQuery方法: attr
$(document).ready(function() { $('.child').attr('rel', function(i, relName) { $(this).appendTo('#' + relName); return relName.replace('&',''); }); });