【问题标题】:How to get third occurence of a class in jquery and add another class to it如何在jquery中第三次出现一个类并向它添加另一个类
【发布时间】:2018-11-16 19:57:16
【问题描述】:

我需要获得第三次出现的类名

类名是coral-buttongroup.rte-toolbar。我怎样才能获得此类的第三次出现,然后在其上附加一些内容。

我试过了

$('.coral-buttongroup.rte-toolbar').eq(2).append('<button  class="desc-count"></button>');

但这不起作用。

【问题讨论】:

  • 你试过 $('.coral-buttongroup.rte-toolbar')[2] 吗?
  • 如果该选择器不起作用,您需要验证它是否准确,因为您的语法看起来是有效的。 eq(2).append('stuff') 将获取结果堆栈的第三个元素,作为 jQuery 对象(因为它的偏移量为 0),并将任何内容附加到它。
  • @muka.gergely [2] 会做和eq(2) 一样的事情,只是它会返回一个原始的DOM 元素,所以他们必须将它包装在$() 中才能使用append。所以实际上两者之间没有区别,而[] 会导致更多的工作要做
  • 如果数组语法给你未定义,那么要么你的选择器不正确,要么该数组没有第三个元素:)
  • 假设你已经加载了 jQuery,并且在元素存在之后有代码

标签: jquery aem


【解决方案1】:

您的代码有效

  • 你有嵌套的双引号,但你修复了它
  • 你需要加载jQuery
  • 您的代码必须等到元素存在

$(function() {
  $('.coral-buttongroup.rte-toolbar').eq(2)
    .append('<button  class="desc-count">Click</button>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="coral-buttongroup rte-toolbar">1</div>
<div class="coral-buttongroup rte-toolbar">2</div>
<div class="coral-buttongroup rte-toolbar">3</div>
<div class="coral-buttongroup rte-toolbar">4</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    相关资源
    最近更新 更多