jquery change attribute

谁都会走 提交于 2019-12-12 11:55:52

问题


i have 4 links and i need to change the href attribute in a rel attribute. i know i cannot do it so i'm trying to get the data from the href attribute, setting a new attribute (rel), inserting the data inside it and then removing the href attibute.

basically i'm doing this:

$('div#menu ul li a').each(function(){
        var lin = $(this).attr('href');
        $('div#menu ul li a').attr('rel',lin);
        $(this).removeAttr('href');


        })
    })

it works but it sets the same rel data in every link i have.

any help?


回答1:


$('div#menu ul li a').each(function(){
    var lin = $(this).attr('href');
    $(this).attr('rel',lin);
    $(this).removeAttr('href');
});



回答2:


Try

$('div#menu ul li a').each(function(){
    var lin = $(this).attr('href');
    $(this).attr('rel',lin);
    $(this).removeAttr('href');


    })
})

Haven't actually ran the code...but that looks like it should do the trick.




回答3:


Change:

$('div#menu ul li a').attr('rel',lin);

To:

$(this).attr('rel',lin);



回答4:


You are probably doing "it" wrong. (meaning there is a better way to do what you are attempting).

but to just answer your question:

$('#menu ul li a').each(function(){
    var lin = $(this).attr('href');
    $(this).attr('rel',lin).removeAttr('href');
});



回答5:


Here is a solid jquery solution:

$(function() {
    $("a.selector").on("click", function() {
        var trigger = $(this.hash);
        trigger.removeAttr("id");
        window.location.hash = this.hash;
        trigger.attr("id", this.hash.replace("#",""));
        return false;
    });
});



回答6:


this is the problem

$('div#menu ul li a').attr('rel',lin);

this line apply changes to any element matches your selector, which in your case will match the four links --use this code instead

$('div#menu ul li a').each(function(){
        var lin = $(this).attr('href');
        $(this).attr('rel',lin);
        $(this).removeAttr('href');    
        })
    })


来源:https://stackoverflow.com/questions/2654328/jquery-change-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!