【问题标题】:how to add id attribute and unique id inside html div tag如何在html div标签中添加id属性和唯一id
【发布时间】:2021-12-25 11:30:22
【问题描述】:

我想在 id attr 中添加 id 属性和唯一 id。我试过但在 id 属性中获取对象

$("div .abc").each(function() {
  $('.abc').attr('id', $(this).uniqueId());
})
[id]::before {
  content: attr(id);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.min.js"></script>
<div class="xyz">
  <div class="abc"></div>
  <div class="abc"></div>
  <div class="abc"></div>
</div>

【问题讨论】:

  • 什么是.uniqueId()?那是一些 jQuery 插件吗?
  • “我想在 id attr 中添加 id 属性和唯一 id” - 为什么?
  • 它将生成唯一的 id 见api.jqueryui.com/uniqueid
  • 哦哦,是的,它是 jQueryui,而不是 jQuery。
  • 我从这里得到了这个但没有工作我是 jQuery 的新手stackoverflow.com/a/21038520/17023923

标签: html jquery jquery-ui


【解决方案1】:

jQueryUI .uniqueId() 方法在内部完成了您需要的所有工作。它返回一个 jQuery 对象,这就是为什么您会看到看起来像一个对象的原因。在.each() 回调中,您只需要

  $(this).uniqueId();

事实上你甚至不需要.each():

  $("div .abc").uniqueId();

将遍历匹配的元素并给每个元素一个唯一的 id 值。

【讨论】:

    【解决方案2】:

    完整代码在这里

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <title>Document</title>
        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
      </head>
      <body>
        <div class="xyz">
          <div class="abc"></div>
          <div class="abc"></div>
          <div class="abc"></div>
        </div>
      </body>
      <script>
        $(".abc").each(function (index) {
          $(this).attr("id", "abc" + index);
        });
      </script>
    </html>
    
    

    【讨论】:

    • 这并不能保证“id”值的唯一性。
    • 如果你想使用 uuid4,这是你的选择。
    • 重点是 OP 尝试使用的 .uniqueId() 函数(错误地)确实保证每个受影响元素的唯一 id 值。
    • 请不要在回答中提供有关您的问题的其他信息。相反,请编辑您的问题。在这种情况下,我已经为你做了,所以请删除这个答案。
    【解决方案3】:

    yu 可以使用每个循环或 for 循环自动增加一个 html 元素的 id

    每个循环都是这样的;

    $(".abc").each(function(i) {
      $(".abc").attr('id', 'id' + i);
    })
    

    或使用 for 循环

    for(var i = 0, i = $(".abc").length, i++){
      $(".abc").attr('id', 'id' + i);
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-10
      • 1970-01-01
      相关资源
      最近更新 更多