2011-04-07 57 views
8

我有一組隨機鏈接,就像這樣:jQuery的 - 添加/附加價值的「相對」屬性

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

他們中有些人可能有rel屬性,有的沒有。

如何在每個鏈接上添加一個值爲rel的屬性,如果鏈接已經有一個,那麼將我的值附加到現有值/值?

另外,如何跳過任何具有某個rel屬性的元素,如rel="ignore"

+0

你是做這個爲SEO的原因?對於大多數搜索引擎蜘蛛來說,客戶端的更改不會被考慮在內。 – daniellmb 2011-04-07 23:37:35

+0

不,我想根據它們的容器將圖像鏈接分組爲組,並且'rel'由一個lightbox插件用於識別畫廊 – Alex 2011-04-07 23:41:00

回答

16

短「東經甜:

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

You can try it here.

+0

...並且是的,它會將rel添加到不具有rel屬性的錨。 – karim79 2011-04-07 23:32:39

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

這應該很好地工作:

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

簡單的迭代在所有的錨,附加你的價值。如果rel不存在curRel將只是空字符串,因此代碼不會中斷。

1

只需使用attr

var add = "some rel to add"; 

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

有點冗長,但是這應該這樣做(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); 
});