仅从前三个标签中获取"id"值,并在输出中用","分隔它们



我有一个情况,希望这里的专家能帮我解决一下。我需要获得前三个标签的"id"值,然后在console.log上打印用逗号分隔的值。

我已经设法从标签中获得值并将其打印在输出上。然而,我不能用逗号分隔它们,问题是我得到的是所有文章的id,而不是只有3篇。

这是我想出来的jquery代码

jQuery(document).ready(function($) {
       $("article").each(function() {
    var info1 = $(this).attr("id");
    var info2 = info1.replace( /[^d]/g, '');
    console.log(info2);
});
});

这是测试

http://jsfiddle.net/0mvjbkhs/1/

请注意,我不能对html做任何改变,我所能做的就是使用jquery完成任务。

请帮助修复我的代码,所以我的输出将看起来像[155569, 155570, 155571]

谢谢你,

使用jQuery的.map()方法返回一个数组;如果需要单个逗号分隔的字符串,请使用JavaScript .join()方法。不要忘记:lt(3),它说你想要前三个:

var arr1st3 = $('article:lt(3)').map(function() {
    return this.id.replace(/[^d]/g, '');
}).get();
console.log( arr1st3 );//OUTPUT: ["155569", "155570", "155571"]
//If you want [155569, 155570, 155571] as output
//use return +this.id.replace(/[^d]/g, ''); instead

jQuery(document).ready(function($) {
  // search by the attribute 
  var ids = $('article')
    // Take only the first three items
    .slice(0, 3)
    // Loop them to return an array
    .each(function() {
      // Get just the id and put that in the array
      return this.attr('id');
    });
  // Format your output
  console.log('[' + ids.join(', ') + ']');
});

http://jsfiddle.net/0mvjbkhs/4/

jQuery(document).ready(function($) {
    var articles = [];
  $("article").each(function() {
    var info1 = $(this).attr("id").replace( /[^d]/g, '');
    articles.push(info1);
    if (articles.length == 3) {
        // break;
        return false;
    }
  });
  console.log('[' + articles.join(', ') + ']');
});

最新更新