亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

jQuery可以提供標簽名稱嗎?

jQuery可以提供標簽名稱嗎?

慕沐林林 2019-11-30 12:49:02
我在HTML頁面上有幾個具有相同類的元素-但是它們是不同的元素類型。我想在遍歷元素時找出元素的標簽名稱-但是.attr不會使用“標簽”或“標簽名稱”。這就是我的意思??紤]頁面上的以下元素:<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元素的ID為rndh2_1rndh4_3分別。關于如何發現“ this”表示的元素的標簽名稱的任何想法?javascript jquery
查看完整描述

3 回答

?
白豬掌柜的

TA貢獻1893條經驗 獲得超10個贊

您可以嘗試以下方法:


if($(this).is('h1')){

  doStuff();

}


查看完整回答
反對 回復 2019-11-30
?
侃侃爾雅

TA貢獻1801條經驗 獲得超16個贊

由于我之前曾經遇到過這個問題,并且對我的情況沒有幫助(我沒有this,但是有一個jQuery選擇器實例)。調用get()將獲得HTML元素,您可以通過該元素獲得nodeName上述內容。


this.nodeName; // In a event handler, 'this' is usually the element the event is called on

要么


$('.hello:first-child').get(0).nodeName; // Use 'get' or simply access the jQuery Object like an array

$('.hello:first-child')[0].nodeName;     // will get you the original DOM element object


查看完整回答
反對 回復 2019-11-30
  • 3 回答
  • 0 關注
  • 617 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號