计算具有特定id的跨度的跨度数

时间:2013-09-22 21:57:23

标签: jquery

如何计算span-s的数量,直到具有特定id的跨度。

例如:

直到具有id =“a5”的跨度是第6 跨度。

<table border="3">
    <tr>
        <td><span id="a2" class="arrow_icon a6" isClicked="0"></span></td>
        <td><span id="a1" class="arrow_icon a1" isClicked="0"></span></td>
        <td><span id="a3" class="arrow_icon a11" isClicked="0"></span></td>
        <td><span id="a4" class="arrow_icon a16" isClicked="0"></span></td>
        <td><span id="a6" class="arrow_icon a2" isClicked="0"></span></td>
    </tr>
    <tr>
        <td><span id="a5" class="arrow_icon a21" isClicked="0"></span></td>
        <td><span id="a7" class="arrow_icon a7" isClicked="0"></span></td>
        <td><span id="a8" class="arrow_icon a12" isClicked="0"></span></td>
        <td><span id="a9" class="arrow_icon a17" isClicked="0"></span></td>
        <td><span id="a10" class="arrow_icon a22" isClicked="0"></span></td>
    </tr>
</table>

我尝试过类似的事情:

var count = 0;
$("span:first").nextUntil("#a5").andSelf().each(function(index) {
     count++;
});
alert(count); // should alert '6'

任何帮助表示赞赏!

5 个答案:

答案 0 :(得分:2)

你不能使用.nextUntil(),因为它会查看兄弟姐妹,而不是你示例中的所有span元素都是兄弟姐妹。将选择器放入$(...)应该生成一个jQuery对象,该对象尊重DOM中元素的顺序,所以可能只是:

var count = 0;
$("span").each(function(i) {
    count++;
    if (this.id === "a5") {return false;} // breaks out of loop when the id is found
});

console.log(count);

答案 1 :(得分:1)

使用.each()循环遍历所有跨度,并使用索引(循环迭代次数)作为计数器:

var c;
$("span").each(function(index, element) {
    if(element.id == "a5") {
        c = index; // set counter to current index value
        return false; // break the each loop
    }
});
alert(c);

http://jsfiddle.net/8rPcN/

答案 2 :(得分:1)

你不能使用nextUntil(),因为他们不是兄弟姐妹。这是我能想到的最佳方式。

var a5index;
$('table span').each(function(idx){
  if( $(this).is('#a5')){
    a5Index = idx;
    return true; // No reason to keep going after we find it...
  }
});

答案 3 :(得分:1)

首先,您的初始选择在第一个<td>...</td>中包含仅一个 span元素。所以你应该改为$("span")...

其次, nextUntil 功能在所选项目的兄弟中进行搜索,只需查看jQuery文档即可确认:

nextUntil specification

这意味着,您的跨度集合会变为......零。为什么?他们的直接父母是<td>...</td>标签,只包含一个范围,所以 none 实际上都有兄弟姐妹。

补救措施非常简单:

var count = 0;

$("span").each(function(i, e){
    if(!$(this).is("#a5"))
        count++; //count it up
    else
        return false; //exit the each function
});

alert(count); //alerts '5', as it should

它起作用的主要原因是因为选择已经按照它们在DOM中呈现的方式进行了排序。否则用它做任何事情都会很困难。

干杯

答案 4 :(得分:0)

使用return false可以提前退出.each循环

var count = 0;
var toId = "a5";
$("span").each(function(){
   count++;
   if(this.id == toId) {
      return false;
   }
});
console.log(count);

或使用.index

使用一行
console.log( $("span").index($("#a5")) );