【问题标题】:Create a href link for 'each hashtags' from JSON file从 JSON 文件为“每个主题标签”创建一个 href 链接
【发布时间】:2016-10-09 03:59:31
【问题描述】:

为“每个主题标签”创建一个 href 链接。

但是,下面的代码仅为 JSON 文件中的“最后一个主题标签”创建 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>'
    ) 
}

【问题讨论】:

    标签: javascript arrays json ajax replace


    【解决方案1】:

    这看起来像是地图的工作! Map 接受一个转换元素的函数,并将该函数应用于数组中的每个元素。它为您返回一个包含所有新值的新数组。我将映射主题标签数组并返回一个包含标记的新数组。然后你就可以将它们插入到 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);
        });
      }
    });
    

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

    【讨论】:

    • 如何将字符串中的主题标签替换为匹配的映射主题标签
    • 如何替换整个内容:“今晚#c..的#a,#b..”与匹配的映射主题标签。与#a, #b 在今晚的 #c
    猜你喜欢
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    相关资源
    最近更新 更多