【问题标题】:Why can't I get .uniqueId() to work with all elements of same class为什么我不能让 .uniqueId() 与同一类的所有元素一起工作
【发布时间】:2018-11-28 19:51:10
【问题描述】:

我有一个<a class="anchor"></a> 元素列表。为什么我不能让uniqueId() 处理它们?这是我所拥有的:

<a href="#" class="anchor">This</a>
<a href="#" class="anchor">This</a>
<a href="#" class="anchor">This</a>
<a href="#" class="anchor">This</a>
$(".anchor").each(function() {
  $(this).uniqueId();
});

我也试过了:

this.uniqueId();

提前致谢。

【问题讨论】:

  • uniqueId() 是一个 jQueryUI 方法,那么您是否包含了 jQueryUI 库以及 jQuery 本身?检查控制台是否有错误。虽然我建议如果您正确构建 HTML,则根本不需要自动生成 id
  • 我用 JQuery UI 测试了它。它工作正常。
  • @zfrisch 更进一步,你不需要 each(): jsfiddle.net/RoryMcCrossan/g95aebxz
  • @RoryMcCrossan 你是对的,但它直接来自 OP。只是想证明它有效。 :)

标签: javascript jquery jquery-ui


【解决方案1】:

简单使用:

$('.anchor').uniqueId();

演示:

$('.anchor').uniqueId();

$('.anchor').each(function() {
  console.log($(this).attr('id'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<a href="#" class="anchor">This</a>
<a href="#" class="anchor">This</a>
<a href="#" class="anchor">This</a>
<a href="#" class="anchor">This</a>

但是,您的代码应该会产生相同的结果。如 cmets 中所述,请确保您已包含 jQuery 和 jQuery UI 的库。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2010-10-28
    • 2021-04-29
    • 2015-03-16
    • 1970-01-01
    • 2011-10-05
    • 2015-08-31
    相关资源
    最近更新 更多