Javascript &引用;配对“;HTML页面上包含类的元素集

Javascript &引用;配对“;HTML页面上包含类的元素集,javascript,jquery,html,Javascript,Jquery,Html,这是问题的后续部分。我的页面上有很多结构,看起来有点像这样: <h2> <span class="stuff">[<a href="whatever">stuff</a>]</span> <span class="moreStuff">Another test</span> </h2> $("my selector").each(function(i) { $(this).attr("cla

这是问题的后续部分。我的页面上有很多结构,看起来有点像这样:

<h2>
<span class="stuff">[<a href="whatever">stuff</a>]</span> <span class="moreStuff">Another test</span>
</h2>
$("my selector").each(function(i) {
    $(this).attr("class", "pair" + i);
    $(this).closest("h2").attr("class", "pair" + i);
}

[]另一项测试

我想将
中的每一个“配对”,例如,给它们相同的类,这样当我选择
时,我也可以选择“对应的”
。我该怎么做(和前面的问题一样,JQuery非常受欢迎)?

第一次回答我自己的问题:我会用这样的方式:

<h2>
<span class="stuff">[<a href="whatever">stuff</a>]</span> <span class="moreStuff">Another test</span>
</h2>
$("my selector").each(function(i) {
    $(this).attr("class", "pair" + i);
    $(this).closest("h2").attr("class", "pair" + i);
}

你说的“选择”是什么意思?我的意思是,选择一个元素。因此
$(“html”)
将选择主
元素。不要使用attr(“class”,value)而是使用addClass(value),这样做您就不会冒在对象上使用以前的任何其他类的风险。