2010-04-16 185 views
4

我有4個鏈接,我需要更改rel屬性中的href屬性。 我知道我不能這樣做,所以我試圖從href屬性獲取數據,設置一個新屬性(rel),在其中插入數據,然後刪除href屬性。jquery更改屬性

基本上我這樣做:

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


     }) 
    }) 

它的工作原理,但它設置在每一個環節我有同樣的相對數據。

有幫助嗎?

+1

'$( '#DIV菜單UL李一')''=== $(這)'您的匿名函數裏面,你有兩組閉括號和括號。 – 2010-04-16 15:51:39

+0

我甚至沒有注意到額外的「})」。男人......我需要吃飯或睡覺。 – 2010-04-16 15:54:00

回答

2

嘗試

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


    }) 
}) 

沒有實際運行的代碼...但是這看起來像它應該做的伎倆。

+0

看起來像我一直捱打! +1給你。 – 2010-04-16 15:52:53

2

變化:

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

要:

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

完美! thnx :) – junray 2010-04-16 16:01:25

0

你可能做的 「它」 是錯誤的。 (這意味着有更好的方法去做你正在嘗試的東西)。

但只是回答你的問題:

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

這裏是一個堅實的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; 
    }); 
}); 
0

這是

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

此行應用更改問題到任何元素匹配您的選擇器,哪個你的情況 將匹配四個環節 --use這個代碼,而不是

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