0

我有搜索 jquery 文档和 SO,但我找不到我所追求的。

我在 php 中创建了跨度,因此它们遵循以下模式:

<span class="om" id="o_1"></span>
<span class="om" id="o_3"></span>
...

我想收集 id 属性中的所有数字,并通过 ajax 将它们作为数据数组(如果需要,json)发送到服务器,并将结果返回给函数:

$.get("/pages/gOboxMeters", function($("span.om") <-- extract id's here ) {alert(data);} )

我现在只是在alert学习它。

什么是正确的代码?

谢谢

4

4 回答 4

1

您可以使用地图

现场演示

numbers = $('.om').map(function(){
  return this.id.replace('o_', '');
}).get().join(',');

jQuery.get( "/pages/gOboxMeters", "yourVariable: " + numbers,
     function(){alert(""sent);
});

您可以在连接中使用其他分隔符

于 2013-04-04T10:58:15.503 回答
1

您还可以使用函数在该数组中的值中创建一个arrayandpusheachjQuery

看演示

var num = new Array;

$(".om").each(function(){
       num.push($(this).attr("id").replace("o_",""));
       $("#result").append($(this).attr("id").replace("o_","")+"<br>"); // just to show result visually
});
于 2013-04-04T11:03:56.907 回答
0

您可以像这样收集和发送值

$(document).ready(function(){
var value = []

$('span.om').each(function(){    
 value.push($(this).attr('id'))});
alert(value);
   $.get("/pages/gOboxMeters",{value : value }, function(){});

});

示例:http: //jsfiddle.net/X5r8r/1120/

于 2013-04-04T11:08:48.640 回答
0

您可以使用.each()jQuery 函数:

  var arr = [];
  $('span.om').each(function(index, item){arr.push($(item).attr('id').substring(2));})

在同一个页面的控制台中,我尝试了以下操作,它工作正常:

var arr = []
$('.mainnavs a').each(function(index, item){arr.push($(item).attr('id').substring(4));})

在此之后,使用 arr 变量进行进一步处理。

于 2013-04-04T11:13:48.590 回答