javascript jQuery - 将值添加/附加到“rel”属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5588746/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:42:06  来源:igfitidea点击:

jQuery - add/append value to "rel" attribute

javascriptjqueryhtmlrel

提问by Alex

I have a set of random links, like this:

我有一组随机链接,如下所示:

<a rel="foo"> ... </a>
...
<a> ... </a>

Some of them may have a relattribute, some not.

其中一些可能具有rel属性,有些则没有。

How can add a relattribute with a value to each link, and if the link already has one, then append my value to the existing value/values?

如何rel向每个链接添加一个带有值的属性,如果链接已经有一个,那么将我的值附加到现有值/值?

Also how can I skip any elements with that have a certain rel attribute, like rel="ignore"?

另外,如何跳过具有特定 rel 属性的任何元素,例如rel="ignore"

回答by karim79

Short 'n sweet:

短暂的甜蜜:

$("a[rel!='ignore']").each(function() {
    this.rel += 'theValue';
});

You can try it here.

你可以在这里试试。

回答by Shadow Wizard is Ear For You

This should work fine:

这应该可以正常工作:

$("a").each(function(index) {
    var curRel = $(this).attr("rel");
    if (curRel !== "ignore")
        $(this).attr("rel", curRel + " my value");
});

Simple iteration over all the anchors, appending your value. If reldoesn't exist curRelwill just be empty string so the code won't break.

对所有锚点进行简单迭代,附加您的值。如果rel不存在curRel将只是空字符串,因此代码不会中断。

回答by sauerburger

var toModify = $('#xxx'); /* or how ever you identify you link */
var currentAttr = toModify.attr('rel');
if(currentAttr != 'ignore'){
    toModify.attr('rel', currentAttr + '_asd');
}

回答by David Tang

Using just attr:

仅使用attr

var add = "some rel to add";

$('a[rel!="ignore"]').attr('rel', function (i, old) {
    return old ? old + ' ' + add : add;
});

回答by matt

A bit verbose, but this should do it (http://jsfiddle.net/dGGFN/):

有点冗长,但这应该可以做到(http://jsfiddle.net/dGGFN/):

var myValue = 'abc';

$.each($('a'), function(idx, item) {
  var a = $(item);
  var rel = $(a).attr('rel');
  $(a).attr('rel', rel + myValue);
});