【问题标题】:jquery - select class elements and add to arrayjquery - 选择类元素并添加到数组
【发布时间】:2012-08-17 15:01:02
【问题描述】:

我想选择所有具有“play”类的元素并将它们添加到数组“esArreglo”中。

html 文件:

<td id="b1" class></td>
<td id="b2" class></td>
<td id="b3" class="play"></td>
<td id="b4" class="play"></td>

代码:

$('td.play').each(function() {
    notas.push(this.id)};

var esArreglo = notas.join(',');

我该如何解决这个问题? 谢谢。

【问题讨论】:

  • 有什么问题?你的代码看起来很好,除了在var esArreglo 语句之前的末尾缺少),即}); 就在notas.push... 之后。并将; 移动到.push() 部分之后。

标签: jquery class select


【解决方案1】:

你可以使用jQuery.map

var esArreglo = $('td.play').map(function() {
  return this.id;
}).get().join(',');

【讨论】:

  • 您在答案中使用的 $.fn.map() 的行为与 $.map() 略有不同。它返回一个 jQuery 对象,而不是数组,因此您必须在 join() 之前调用 get() 才能使您的代码正常工作。
【解决方案2】:

可能因为您在.each 中缺少);

$('td.play').each(function() {
    notas.push(this.id)
});

var esArreglo = notas.join(',');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    相关资源
    最近更新 更多