jQuery jquery更改属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2654328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery change attribute
提问by junray
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.
我有 4 个链接,我需要更改 rel 属性中的 href 属性。我知道我不能这样做,所以我试图从 href 属性中获取数据,设置一个新属性 (rel),将数据插入其中,然后删除 href 属性。
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.
它有效,但它在我拥有的每个链接中设置了相同的 rel 数据。
any help?
有什么帮助吗?
回答by hellYEAH
$('div#menu ul li a').each(function(){
var lin = $(this).attr('href');
$(this).attr('rel',lin);
$(this).removeAttr('href');
});
回答by E-man
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.
还没有真正运行代码......但看起来它应该可以解决问题。
回答by awgy
Change:
改变:
$('div#menu ul li a').attr('rel',lin);
To:
到:
$(this).attr('rel',lin);
回答by David Murdoch
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');
});
回答by rkingon
Here is a solid jquery solution:
这是一个可靠的jquery解决方案:
$(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;
});
});
回答by Peter Isaac
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');
})
})