2013-04-11 49 views
0

我正在處理用戶更改span元素順序的代碼,如他所願。 我需要收集跨度元素的順序,並把它放在例如一個變量,如果爲了看如下:收集訂單<span> -elements

<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 「

回答

2

如果有一個可識別的家長,你可以這樣做:

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

但是,如果我想嘗試這個,我想補充一些class ES和data-id s到混合:

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')); 
}); 
+1

你爲什麼要做substring(5)? – Martinsos 2013-04-11 17:00:59

+2

因爲OP只需要id的整數部分(如果我正確理解他的話) – Steve 2013-04-11 17:02:04

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

,你將不得不在陣列IDS IDS。 對於示例,這將是IDS = [ 「跨越-2」, 「跨度-3」, 「跨度-5」, 「跨度-4」, 「跨度-1」]

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); 
}); 

對於只獲得跨度IDS:

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); 
}); 
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/