2012-09-18 30 views
0

我有code here on jsfiddle無法使用jquery在DOM上添加屬性

我們正在使用jquery 1.4.4無法更新到更新的版本,在那裏我可以讓我的代碼工作。

因此,我需要在domready或pageload上,將attr添加到衆多<a標籤中。有人可以幫助我找出一種方法,這是可能的JavaScript和/或所需的jQuery版本。

謝謝。

+2

爲什麼使用事件屬性,如果您有jQuery的身邊? – Bergi

+0

@Bergi這是一個很好的觀點! – Anicho

回答

1

您可以使用.attr(index, callback)過程做到這一點很容易地象下面這樣:

$('a').attr('href', function(index, oldAttr) { 
    if (oldAttr.indexOf('test') >= 0) { 
     $(this) 
      .removeAttr('onclick') 
      .get(0) 
      .setAttribute("onclick", "test"); 
    } 
});​ 

Demo

但是,如果你想使用.each()然後嘗試像以下:

$('a').each(function(index, element) { 
    var el = $(element), 
     hasHref = !el.attr('href'); // return true, if no href 
    if(!hasHref) { 
     var href = el.attr('href'); 
     if(href.match('test').length || href.match('test-page').length) { 
     el 
      .removeAttr("onclick") 
      .get(0) 
      .setAttribute("onclick", "test"); 
     } 
    } 
});​ 

Demo

+0

這不工作:http://jsfiddle.net/3mZVc/2/ – Anicho

+0

它與我原來的相同,但刪除,但不添加回來。 – Anicho

+0

@Anicho檢查我的更新 – thecodeparadox

相關問題