簡體   English   中英

如何使用jQuery為HTML中的每個元素設置唯一ID

[英]how to set unique id for every element in html using jQuery

我在我的html中有很多類,但是我希望每個類(如果需要更改,請輸入id)是唯一的。 我的代碼中有很多class="answer-to-q" ,當我單擊特定的代碼時,該<div>應該向下滑動。

 <div style="text-align: right;margin: 20px 20px 0 0">
      <p class="answer-to-q">please log in
      <span uk-icon="icon:  plus-circle"></span>
       </p>
  </div>

jQuery的:

 $(".answer-to-q").click(function () {
       $(".post-a-answer-div").slideDown("slow");
  });

理想情況下,我認為您應該在生成HTML時設置ID,但是如果這不可能,那么類似的事情可能起作用嗎? 我使用的是數據屬性而不是ID,因為這似乎更合適,但是如果您確實需要使用'em,則可以對其進行修改以使用ID。

// Add data attributes
var count = 1;
$('.answer-to-q').each(function(){
  $(this).attr('data-q', count);
  $('body').find('.post-a-answer-div:not([data-a])').first().attr('data-a', count);
  count++;
});

// Toggle on click
$('.answer-to-q').click(function(){
  var target = $(this).attr('data-q');
  $('[data-a="'+target+'"]').toggle();
});

示例: https//codepen.io/anon/pen/xzaBgM

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM