收集<span> -elements </span>的顺序

时间:2013-04-11 16:53:59

标签: jquery html

我正在编写一个代码,用户可以根据需要更改span元素顺序。 我需要收集span元素的顺序并将其放在变量中,例如,如果顺序如下所示:

<span id="span-2">[<a class="move-up">Up</a>/<a class="move-down">Down</a>]</span>
<span id="span-3">[<a class="move-up">Up</a>/<a class="move-down">Down</a>]</span>
<span id="span-5">[<a class="move-up">Up</a>/<a class="move-down">Down</a>]</span>
<span id="span-4">[<a class="move-up">Up</a>/<a class="move-down">Down</a>]</span>
<span id="span-1">[<a class="move-up">Up</a>/<a class="move-down">Down</a>]</span>

然后,变量将是“2,3,5,4,1”

4 个答案:

答案 0 :(得分:2)

var ids = [];
$("span").each(function(index) {
    ids.push($(this).attr('id'));
});

你将在数组 ids 中有id。 对于您的示例,它将是 ids = [“span-2”,“span-3”,“span-5”,“span-4”,“span-1”]

答案 1 :(得分:2)

如果有可识别的父母,您可以这样做:

var order = new Array();
$("#parentID span").each(function(){
    order.push($(this).attr('id').substring(5));
});

但是,如果我尝试这样做,我会在其中添加一些class es和data-id

HTML:

<span class="mySpan" data-id="2" id="span-2">[<a class="move-up">Up</a>/<a class="move-down">Down</a>]</span>
<span class="mySpan" data-id="3" id="span-3">[<a class="move-up">Up</a>/<a class="move-down">Down</a>]</span>
<span class="mySpan" data-id="5" id="span-5">[<a class="move-up">Up</a>/<a class="move-down">Down</a>]</span>
<span class="mySpan" data-id="4" id="span-4">[<a class="move-up">Up</a>/<a class="move-down">Down</a>]</span>
<span class="mySpan" data-id="1" id="span-1">[<a class="move-up">Up</a>/<a class="move-down">Down</a>]</span>

JS:

var order = new Array();
$(".mySpan").each(function(){
    order.push($(this).attr('data-id'));
});

答案 2 :(得分:1)

为了获得跨度:

var spanArray = []; //Contain all spans in the proper order (2,3,5,4,1)

$("span").each(function(i){
     spanArray.push($("span")[i]);
     console.log(i + ": " + this.id);
});

仅获取span id:

var spanIDsArray = []; //Contain all span ids in the proper order (2,3,5,4,1)

$("span").each(function(i){
     spanIDsArray.push(this.id);
     console.log(i + ": " + this.id);
});

答案 3 :(得分:0)

Your variable will be look like this:

$(document).ready(function(){
 var spnArray = [];
 $("span").each(function(i)
 {
    spnArray.push($(this).attr("id"));
             });
                 console.log(spnArray);
    });

参见DEMO:

http://jsfiddle.net/KcRTm/