如何使用jQuery分离出字符串中的元素

时间:2016-05-18 07:19:19

标签: javascript jquery html ajax

我已经对外部网站进行了Ajax调用,以从特定元素中获取一些信息并将其作为字符串返回到我的网站上。

这是AJAX调用的代码:

$.ajax({
   url: 'http://cors.io/?u=http://www.spotlight.com/6298-9058-7917',
   type: 'GET',
   success: function(res) {
      var data = $.parseHTML(res);           

       $(data).find('.credit').each(function(){
          $('#credits').append($(this).html());
     });

   }
 });

这将获取外部网站上名为.credit的div的所有内容,并返回如下所示:

<div id="credits">
    <span class="creditYear">2010</span>, <span class="creditProductionType">Television</span>, <span class="creditCharacterRole">Cop Nicola Lanza</span>, <span class="creditProductionName">“Un posto al sole”</span>, <span class="creditCompany">Grundy</span>, <span class="creditDirector">Various</span><span class="creditYear">2008</span>, <span class="creditProductionType">Television</span>, <span class="creditCharacterRole">Lawyer Moroni</span>, <span class="creditProductionName">“Il Bene e il Male”</span>, <span class="creditCompany">Italy</span>, <span class="creditDirector">Giorgio Serafini</span>
</div>

显然,在我的页面上,这看起来有点混乱,我希望能够做的就是把它很好地整理成一张桌子。因此,对于每组结果(即年份,生产,角色角色,生产名称,公司,董事),表格中应该有一行,如下所示:

<table>
    <tr>
        <td class="year"></td>
        <td class="production_type"></td>
        <td class="character_role"></td>
        <td class="production_name"></td>
        <td class="company"></td>
        <td class="director"></td>
        <td class="director"></td>
    </tr>
</table>

...但每组结果只有一行。是否可以附加每个相应的信用(来自AJAX调用)并将其显示在我的表中?

1 个答案:

答案 0 :(得分:0)

您可以通过将每个跨度中的数据复制到表格的相关单元格来实现:

成功回调:

// Set up the table however you want it to be formatted
var $tableTemplate = $('<table><tr>' +
  '<td class="year"></td>' +
  '<td class="production_type"></td>' +
  '<td class="character_role"></td>' +
  '<td class="production_name"></td>' +
  '<td class="company"></td>' +
  '<td class="director"></td>' +
  '</tr></table>');

$(data).find('.credit').each(function(){
  // Copy the data from the request to a copy of the table
  var $newTable = $tableTemplate.clone();
  var $creditData = $(this);
  $newTable.find('.year').text($creditData.find('.creditYear').text());
  $newTable.find('.production_type').text($creditData.find('.creditProductionType').text());
  $newTable.find('.character_role').text($creditData.find('.creditCharacterRole').text());
  $newTable.find('.production_name').text($creditData.find('.creditProductionName').text());
  $newTable.find('.company').text($creditData.find('.creditCompany').text());
  $newTable.find('.director').text($creditData.find('.creditDirector').text());

  // And append it to your div (or whatever you want to put it in)
  $('#credits').append($newTable);
}

演示:https://jsfiddle.net/p5zetyam/