2014-03-04 38 views
0

想要查找內容中的所有標題標籤,並檢查每個標籤有id屬性,如果沒有,然後添加id屬性使用jquery

找到所有標題標籤,並檢查每個標籤有id屬性,如果沒有添加id屬性使用jquery

下面是我的代碼:

var headings = $("#edited_content").find("h1,h2,h3,h4,h5,h6"); 
    $.each(headings, function (i, heading) { 
     attributes = heading.attributes 
     $.each(attributes, function (j, value) { 
      if (value.name == 'id') { 
       alert("id present"); 
      } else { 
       alert("id absent"); 
       $(this).attr('id', i); 
      } 
     }); 
    }); 

回答

2

嘗試一個簡單的

var headings = $("#edited_content").find("h1,h2,h3,h4,h5,h6"); 
headings.attr('id', function(i, id){ 
    return id || 'prefix-' + i 
}) 

演示:Fiddle

如果你願意,你可以使用未()過濾微調像headings.not('[id]').attr(...)

+0

使用的編號爲ID是不是在大多數瀏覽器相當有效。 – gdoron

+0

@gdoron在html5中是有效的....但在CSS中它不會工作....任何方式,我們可以很容易地添加一個前綴到編號 –

+0

非常感謝。它的工作是我期望的。 – user2138489

0

試試這個:

if ($(this).attr("id"))) { 
     alert("id present"); 
    } else { 
     alert("id absent"); 
     $(this).attr('id', i); 
    } 
相關問題