![](/img/trans.png)
[英]Fetching “id” from first 5 tags and separate them with comma in output using pure javascript
[英]Get "id" values from first three tags only and separate them with "," in output
我有一个情况,希望这里的专家帮我解决一下。 我需要获取前三个标签的“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(', ') + ']');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.