0

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

<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

4 回答 4

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

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

于 2013-04-11T16:55:53.360 回答
2

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

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

但是,如果我尝试这个,我会添加一些classes 和data-ids :

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'));
});
于 2013-04-11T16:59:02.437 回答
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);
});

仅获取跨度 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);
});
于 2013-04-11T16:56:26.067 回答
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);
    });

见演示:

http://jsfiddle.net/KcRTm/

于 2013-04-11T17:03:01.807 回答