jquery - Javascript,为所有相同类型的元素添加动态类

标签 jquery html css

我想知道如何使用 javascript 将动态类添加到 html 页面上特定类型的所有元素?

我需要它来区分我页面中的输入元素。

例子:

<p class="n+1">input</p>
<p class="n+2">input</p>

有办法吗?

最佳答案

您使用$() 选择元素,然后通过addClass 循环添加一个类。传入函数; jQuery 将使用文档中每个元素的从 0 开始的索引调用该函数。

First P gets class="p1", second P gets class="p2" etc

因为索引是从 0 开始的,所以我们必须给它加一:

$("p").addClass(function(index) {
    return "p" + (index + 1);
});

实例:

$("p").addClass(function(index) {
  return "p" + (index + 1);
});
.p1 {
  color: blue;
}
.p2 {
  color: green;
}
.p3 {
  color: #990;
}
<p>one</p>
<p>two</p>
<p>three</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

关于jquery - Javascript,为所有相同类型的元素添加动态类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32339473/

相关文章:

jquery - HTML 表到 JSON

javascript - 在 JavaScript 工具 InfoVis 中隐藏 canvas 元素之外的 HTML

css - 用于在特定站点上导入 CSS 文件的浏览器扩展

html - 你能在 IE 中的表格行上放置渐变吗?

css - 更改 fa-money 图标上的文字

javascript - Jquery onload 每个循环很简单

javascript - 函数中的 jQuery preventDefault

javascript - 通过 Javascript 更改 CSS 属性

JavaScript/jQuery 2 下拉菜单在页面加载时具有相同的选择选项

javascript - 使用 .html() 时,jQuery 会从字符串中去除一些 html 元素吗?