我有具有相同類別的HTML頁面上的幾個元素 - 但他們是不同的元素類型。我想查找元素的標籤名稱,因爲我循環它們 - 但.attr不採用「標記」或「標記名稱」。jQuery能否提供標籤名稱?
這裏是我的意思。考慮一個頁面上的這些元素:
<h1 class="rnd">First</h1>
<h2 id="foo" class="rnd">Second</h2>
<h3 class="rnd">Third</h3>
<h4 id="bar" class="rnd">Fourth</h4>
現在我想運行這樣的事情,以確保如果沒有已經定義我的元素都有一個id:
$(function() {
$(".rnd").each(function(i) {
var id = $(this).attr("id");
if (id === undefined || id.length === 0) {
// this is the line that's giving me problems.
// .attr("tag") returns undefined
$(this).attr("id", "rnd" + $(this).attr("tag") + "_" + i.toString());
}
});
});
結果我會就像H2和H4元素分別具有
rndh2_1
rndh4_3
。
我如何能發現由「本」所代表的元素的標記名稱的任何想法?
也許答案就在這裏:http://stackoverflow.com/a/8355251/271103 – 2012-07-26 11:54:58