开发者

Javascript replace has no effect

This is the jQuery:

<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>

With this relevant HTML:

<div rel="MadDogs&EnglishmenHandpaintedfigurines" id="Figurines" class="category section child">
     <h3 clas开发者_如何学Pythons="categoryTitle">Figurines</h3>               
</div>

But for some reason, the replace has no effect whatsoever!


replace returns string with replaced data. So you need to assign back to your variable.

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


replace() doesn't change the original string, it returns a new one.


It's not updating because you're not assigning the result to anything.

Try this instead:

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


Here's a neat way to write it, using the callback version of attr basically every jQuery method:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜