从JSON文件为'each hashtags'创建一个href链接

时间:2016-06-08 18:19:57

标签: javascript arrays json ajax replace

为'each hashtags'创建一个href链接。

但是,下面的代码仅为JSON文件中的“last hashtag”创建href链接。

迭代JSON数组

rows
[ ], [ ], 
[ 
    content: "With the #a b, c at tonight's ..",
    hashtags: [
     "a",
     "b",
     "c" 
],

$.ajax('https://rest.xyz.com/..', {
  type: 'GET', 
  dataType: 'json',
  success: function( data ) { 
    for(i in data.rows[3].hashtags){
      content3 = data.rows[3].content.replace(
        new RegExp('#'+data.rows[3].hashtags[i], 'g'), 
        '<a href="https://x.com/hashtags/'+      
        data.rows[3].hashtags[i]+'"'+
        'target="_blank">'+'#'+data.rows[3].hashtags[i]+'</a>'
    ) 
}

1 个答案:

答案 0 :(得分:1)

这看起来像地图的工作! Map采用转换元素的函数,并将该函数应用于数组中的每个元素。它为您提供了一个包含所有新值的新数组。我会映射hashtags数组并返回一个包含标记的新数组。然后你可以将它们插入dom!

$.ajax('https://rest.xyz.com/..', {
  type: 'GET', 
  dataType: 'json',
  success: function( data ) {
    data.rows[3].hashtags.map(function(hashtag) {
      return '<a href="https://x.com/hashtags/' +
             hashtag +
             'target="_blank">#' +
             hashtag +
             '</a>';
    })
    .forEach(function(link) {
      // Do stuff here with each one!
      // $('body').append(link);
    });
  }
});

当然,您可以跳过地图,只需每个链接上的每个链接,创建标记并立即插入即可。为了便于阅读,我将它们分为两个步骤。