使用jquery,当元素不是按连续顺序排列时,如何返回具有下一个连续ID的元素?

Using jquery, how do I return an element with the next consecutive ID when the elements aren't in consecutive order?

本文关键字:元素 连续 返回 下一个 ID jquery 顺序 使用 排列 何返回      更新时间:2023-09-26

按照下面的例子,我有一个分组的链接数组。链接的ID是连续编号的,但链接本身的顺序不是连续的。我知道如何返回点击链接的href和ID,但我也想获得链接的href与下一个连续的ID,当它成为选定的元素,获得下一个等等。当元素本身是连续的时候我知道怎么做但是当它们像这样的时候就不知道了。任何帮助都将是非常感激的。

我HTML

<div id="container">
<div class="group">
<a class="clickable" id="itemid-01" href=""></a>
<a class="clickable" id="itemid-04" href=""></a>
</div>
<div class="group">
<a class="clickable" id="itemid-02" href=""></a>
<a class="clickable" id="itemid-05" href=""></a>
</div>
<div class="group">
<a class="clickable" id="itemid-03" href=""></a>
<a class="clickable" id="itemid-06" href=""></a>
</div>
</div>

我的脚本
$(document).ready(function(){
$('.clickable').click(function(e){
e.preventDefault();
var this_href = $(this).attr('href');
var this_ID = $(this).attr('id');
var next_ID = //this is the part I can't work out
});
});

如果我理解正确的话,这个应该可以。我添加if语句只是为了在数字小于10时捕获后面的零。对于大于100的数字,你需要做类似的事情。

$(document).ready(function(){
    $('.clickable').click(function(e){
    e.preventDefault();
    var this_ID = $(this).attr('id');
    var id_pieces = this_ID.split('-');
    var currentId = parseInt(id_pieces[1]);
    var next_ID = '';
    if(currentId>=10){
        next_ID = id_pieces[0]+'-'+(currentId+1);
    }else{
        next_ID = id_pieces[0]+'-0'+(currentId+1);
    }
    console.log(next_ID);
    });
    });

我不确定你的标记的范围是关于你计划在屏幕上有多少元素。无论哪种情况,给定您设置它的方式,您可以这样做:

var thisId = $(this).attr('id');
var nextId = null;
//use some regex to get the id from the end of the string
var matches = thisId.match(/'d+$/);
//if it finds a matching integer...
if (matches) {
    //parse out the integer and increment it by 1
    var nextIdInt = parseInt(matches[0], 10);
    nextIdInt++;
    //build the next id string:
    //if less than 10, it addes a leading zero, otherwise just leaves it as is
    nextId = (nextIdInt < 10) ?  "itemid-" + "0" + nextIdInt : "itemid-" + nextIdInt;
}
if (nextId) {
    //do something here with the next id if it is not null
}

如果我要这样做,我可能会通过使用自定义属性使自己更容易一些。这将避免使用正则表达式或任何字符串操作,并将使代码更简单。

在你的'clickable'锚上,给它们一些索引属性,像这样:

<a class="clickable" id="itemid-01" href="" data-index="1"></a>

那么你的js可以简单地:

var thisId = $(this).attr('id');
var nextId = null;
//increment the index and store it in a variable
var nextIndex = parseInt($(this).attr('data-index'), 10) + 1;
//get the next element
var nextElement = $('a.clickable[data-index="' + nextIndex + '"]');
//probably smart to make sure we found something...
if (nextElement.length > 0) {
    //if you want the id
     nextId = nextElement.attr('id');
}

如果你不希望它是可读的你想要的是下一个id:

var thisId = $(this).attr('id');
var nextId =  $('a.clickable[data-index="' + (parseInt($(this).attr('data-index'), 10) + 1) + '"]').attr('id');

Here's fiddle