使用jQuery选择类的下一个实例

Select by next instance of class with jQuery

本文关键字:下一个 实例 jQuery 选择 使用      更新时间:2023-09-26

我希望转换一个函数,按id选择给定类的下一个实例。

代码如下:

function swap3(oldDivId, newDivId) {
var oldDiv = document.getElementById(oldDivId);
var newDiv = document.getElementById(newDivId);
oldDiv.style.display = "none";
newDiv.style.display = "block";
}

假设你有这样的HTML:

<div id="test"></div>
<img>
<br>
<div></div>
<input>
<div class="abc">Found it</div>
<div class="cdf"></div>

更新于2021年

原来的答案现在已经很老了。由于原始问题有jQuery标记,因此答案保持有效和可用。但是,对于那些希望看到不依赖于jQuery的更新JavaScript代码的人来说,看看querySelector现在是如何令人敬畏的:

const next = document.querySelector('#test ~ .abc')
next.textContent = 'Yeah, you found it!'

因此,秘诀是使用匹配第二个元素的所有迭代的通用兄弟组合子,但使用只返回第一个匹配的querySelector。

原始回答

通过id选择第一个div:

var some = $("#test");

然后您想要找到abc类的下一个div:

var next = some.nextAll("div.abc");

假设您想要一个变量作为className:

var x = "abc";
var next = some.nextAll("div." + x);

如果我理解你的问题:

function nextItem(className) {
    return $('#ID').closest('.' + className);
}

using close: http://api.jquery.com/closest/

根据jQuery中的ID选择:

$('#class_name')

在jQuery中按类选择:

$('.class_name')

获取jQuery中的下一个项目:

$('.class_name').next('.class_name')

使用这个,你可以像

这样做
// Something to remember the current element
var currentElement = false;
function getNext(className)
{
    // First time, there will be no current element
    if (!currentElement)
    {
        currentElement = $('.' + className);
        return currentElement;
    }
    // Other times...
    currentElement = $(currentElement).next('.' + className);
    return currentElement;