首页 > 解决方案 > jQuery val() 给出奇怪的输出

问题描述

我正在尝试从 discogs 获取曲目列表,控制台中的输出是文件,但使用val()

这是我的代码

$.each(data.tracklist, function(index, TrackName) {
  console.log(TrackName.title); // getting the tacklist 
  $("#album_desc").val(TrackName.title); // getting Hitchhiker 
})

这个 html

<textarea name="album_desc" id="album_desc" class="bbcode_editor" cols="60" rows="8"></textarea>

不是控制台中的任务列表 API 端点https://api.discogs.com/releases/10927583

标签: javascriptjquery

解决方案


您可以将变量作为数组并推送该数组中的所有标题。在为 增加价值的同时textarea,使用Array#joinwith\n

let data = {
  "tracklist": [{
      "duration": "",
      "position": "1",
      "type_": "track",
      "title": "Sorry Not Sorry"
    },
    {
      "duration": "",
      "position": "2",
      "type_": "track",
      "title": "Tell Me You Love Me"
    },
    {
      "duration": "",
      "position": "3",
      "type_": "track",
      "title": "Sexy Dirty Love"
    },
    {
      "duration": "",
      "position": "4",
      "type_": "track",
      "title": "You Don't Do It For Me Anymore"
    },
    {
      "duration": "",
      "position": "5",
      "type_": "track",
      "title": "Daddy Issues"
    },
    {
      "duration": "",
      "position": "6",
      "type_": "track",
      "title": "Ruin The Friendship"
    },
    {
      "duration": "",
      "position": "7",
      "type_": "track",
      "title": "Only Forever"
    },
    {
      "duration": "",
      "position": "8",
      "type_": "track",
      "extraartists": [{
        "join": "",
        "name": "Lil Wayne",
        "anv": "",
        "tracks": "",
        "role": "Featuring",
        "resource_url": "https://api.discogs.com/artists/1065010",
        "id": 1065010
      }],
      "title": "Lonely"
    },
    {
      "duration": "",
      "position": "9",
      "type_": "track",
      "title": "Cry Baby"
    },
    {
      "duration": "",
      "position": "10",
      "type_": "track",
      "title": "Games"
    },
    {
      "duration": "",
      "position": "11",
      "type_": "track",
      "title": "Concentrate"
    },
    {
      "duration": "",
      "position": "12",
      "type_": "track",
      "title": "Hitchhiker"
    }
  ]
}
let allTitles = [];
$.each(data.tracklist, function(index, TrackName) {
  allTitles.push(TrackName.title);
});
$("#album_desc").val(allTitles.join('\n'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea name="album_desc" id="album_desc" class="bbcode_editor" cols="60" rows="8"></textarea>


推荐阅读