开发者

Javascript replace has no effect

开发者 https://www.devze.com 2023-04-12 15:19 出处:网络
This is the jQuery: <script type=\"text/javascript\"> $(document).ready(function(){ var relName; $(\'.child\').each(function() {

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

精彩评论

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

关注公众号