Разбор HTMLHtmlElement в Javascript - PullRequest
       18

Разбор HTMLHtmlElement в Javascript

0 голосов
/ 24 января 2019

У меня есть функция Javascript, возвращающая объект с объектом HTMLHtmlElement, который я хотел бы проанализировать:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://someothersite.com/widgets/whatson.js"></script>
<script src="https://someothersite.com/widgets/jquery-deparam.js"></script>
<script>
    var configuration = {
      schedule: 'now'
    };

    if ( window.location.search ) configuration = $.extend({}, configuration, $.deparam( (window.location.search).replace('?','') ));

    $(function(){
        var content = $('div#output').whatsOn( configuration );
        console.log( $("div#output").html() );
   });
</script>

Вышеупомянутая функция whatsOn заполняет мой выходной div возвращаемым HTML-содержимым, но журнал консоли ничего не выводит,Если я запишу content в консоль, это будет init объект с данными, которые я бы хотел проанализировать.Если я добавлю следующее, он отправит [object HTMLHtmlElement] на консоль со всеми данными на консоль:

var html = content.context.childNodes[1];
console.log( html );

Как я могу разобрать этот HTML?То, что мне нужно, это элемент innerText переменной html выше.Однако, если я перейду на content.context.childNodes[1].innerText, я ничего не получу.

ОБНОВЛЕНО

Вот код, вставленный:

/**
 *  Source for the Daily and Weekly Widgets
 *  Both of these widgets are rendered via the custom whatsOn Jquery plugin which is implemented via this script
 */
;
(function ($, window, document, undefined) {

  /*
   === Begin async caching functions ===
   Asynchronous Caching Code
   The below code seems to be a direct copy of the code from https://learn.jquery.com/code-organization/deferreds/examples/
   This code ensures that multiple requests are not made for loading the same data/resource.

   Generic cache factory (below)
   One promise is cached per URL.
   If there is no promise for the given URL yet, then a deferred is created and the request is issued.
   If it already exists, however, the callback is attached to the existing deferred.
   */
  $.cacheFactory = function (request) {
    var cache = {};
    return function (key, callback) {
      if (!cache[ key ]) {
        cache[ key ] = $.Deferred(function (defer) {
          request(defer, key);
        }).promise();
      }
      return cache[ key ].done(callback);
    };
  };

  // Every call to $.cacheFactory will create a cache respository and return a cache retrieval function
  $.template = $.cacheFactory(function (defer, url) {
    $.ajax({
      url: url,
      data: $.template.params,
      dataType: 'jsonp',
      success: defer.resolve,
      error: defer.reject,
      complete: defer.always
    });
  });
  // === End async caching functions


  // This function handles rendering template markup and data
  $.renderTemplate = function (data, elem, options) {
    var label = ( !options.label ) ? elem.addClass('whatson-hidden') : '';
    return elem.empty().append(data) && label;
  };

  // Handles error message display
  $.errorMessage = function (elem) {
    return elem.append('error');
  };


  /*
    === Begin .whatsOn plugin functions ===
    The following functions create a jquery plugin which can be executed on a JQuery element to render the whatson widget
    The .whatsOn() functions are added to $.fn in order to create this plugin
      - see https://learn.jquery.com/plugins/basic-plugin-creation/
  */
  $.fn.whatsOn = function (options) {

    // Do not initialize the widget if it has already been initialized, or if the station param is missing
    if (this.data('whatson-init') || !options.station) {
      return;
    }
    this.data('whatson-init', true); // widget-initialized flag


    options = $.extend({}, $.fn.whatsOn.options, options);

    // Force fix the old widget calls that do not use iframes.
    if (options.env == 'http://composer.nprstations.org') options.env = 'https://api.composer.nprstations.org/v1';

    $.fn.whatsOn.env = options.env;// Determines which API request URL to use

    // Add CSS stylesheet
    var css = document.createElement('link');
    css.setAttribute('rel', 'stylesheet');
    css.setAttribute('type', 'text/css');
    css.setAttribute('href', options.assets + '/widgets/css/v2.css');
    document.getElementsByTagName('head')[0].appendChild(css);


    /*
     Return the plugin object
     When you filter elements with a selector ($('.myclass')), it can match more than only one element.
     With each, you iterate over all matched elements and your code is applied to all of them.
    */
    return this.each( function () {// BEGIN Return the plugin.

      var elem = options.elem = $(this);
      var ucs = options.station;
      var schedule = options.schedule;
      var times = options.times;
      var next = options.next;
      var show_song = options.show_song || null;
      var display_style = options.style || null;
      var request_url;

      // The buy links
      var hide_itunes = options.hide_itunes || null;
      var hide_amazon = options.hide_amazon || null;
      var hide_arkiv = options.hide_arkiv || null;

      if (!options.affiliates) options.affiliates = {};
      if (options.itunes) options.affiliates.itunes = options.itunes;
      if (options.amazon) options.affiliates.amazon = options.amazon;
      if (options.arkiv)  options.affiliates.arkiv = options.arkiv;

      elem.addClass('whatson-wrap');// Add widget class

      $("body").attr('id', 'nprds_widget'); // Add an ID to the body of the document

      // Ensure that the moment() JS plugin is available, if not, then add and load it (http://momentjs.com/docs/)
      if (!window.moment) {
        $.getScript('https://composer.nprstations.org/widgets/js/moment.isocalendar.js').done(function (script) {
          builder();// Build plugin function (see below)
        });
      } else {
        builder();// Build plugin function (see below)
      }


      // This function builds the plugin, it does all of the setup required
      function builder() {// BEGIN build plugin function

        // Set the date/range for the widget header.  If its the daily widget use a date, for the weekly widget use a range
        var req_date = ( options.schedule === 'week' )
          ? moment().isoday(1).format('YYYY-MM-DD') + ',' + moment().isoday(7).format('YYYY-MM-DD')
          : moment().format('YYYY-MM-DD');

        request_url = $.fn.whatsOn.env + '/widget/' + ucs + '/' + schedule;

        $.template.params = {
          format: 'jsonp',
          date: req_date,
          times: times,
          show_song: show_song || null,
          style: display_style || null,
          hide_itunes: hide_itunes || null,
          hide_amazon: hide_amazon || null,
          hide_arkiv: hide_arkiv || null,
          itunes: options.affiliates.itunes || null,
          amazon: options.affiliates.amazon || null,
          arkiv: options.affiliates.arkive || null
        };

        // Pull out empty fields
        if (!$.template.params.itunes) delete $.template.params.itunes;
        if (!$.template.params.amazon) delete $.template.params.amazon;
        if (!$.template.params.arkiv)  delete $.template.params.arkiv;
        if (!$.template.params.show_song)  delete $.template.params.show_song;
        if (!$.template.params.style)  delete $.template.params.style;
        if (!$.template.params.hide_itunes)  delete $.template.params.hide_itunes;
        if (!$.template.params.hide_amazon)  delete $.template.params.hide_amazon;
        if (!$.template.params.hide_arkiv)   delete $.template.params.hide_arkiv;

        // force now playing to an uncached request
        if (schedule === 'now') request_url = request_url + '?bust=' + ~~(Math.random() * 1E9);

        /*
         $.template(request_url) = Request widget data (from cache or a new request), uses cacheFactory (see code at the top of this script)
         When the data has been received, handle the construction and rendering of the HTML
        */
        $.when( $.template(request_url) ).done( function (data) {

          $.renderTemplate(data, elem, options);

          // Set up the widget header
          if (schedule === 'week') {
            var week_of = moment().isoday(1).format('[Week of] MMMM Do, YYYY');
            $.fn.whatsOn.header(elem, week_of, options);
          }
          if (schedule === 'day') {
            var day_date = moment().format('dddd, MMMM Do, YYYY');
            $.fn.whatsOn.header(elem, day_date, options);
          }

          // Add a handler for when an Itunes link is clicked
          $('.itunes-link').on('click', function (e) { // BEGIN itunes link click handler

            e.preventDefault();// If this method is called, the default action of the event will not be triggered.

            var searchUrl = $(this).attr('href').split('?');
            var forwardTo = '';
            var searchPairs = searchUrl[1].split('&');
            var searchTerms = '';
            var affiliate = '';

            $.each(searchPairs, function (key, value) {
              var pairs = value.split('=');
              if (pairs[0] == 'at') {
                affiliate = pairs[1];
              }
              else {
                searchTerms = searchTerms + ' ' + pairs[1];
              }
            });

            $.ajax({
              url: 'https://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/wsSearch?entity=musicTrack&country=US&term=' + searchTerms + '&at' + affiliate + '&limit=1&callback=?',
              type: 'GET',
              dataType: 'jsonp',
              success: function (data) {
                console.log('data', data)
                if (data.resultCount > 0) {
                  if (data.results[0].collectionViewUrl) {
                    forwardTo = data.results[0].collectionViewUrl;
                  }
                  else {
                    forwardTo = data.results[0].artistViewUrl;
                  }
                }
                else {
                  forwardTo = 'https://itunes.apple.com/us/';
                }
                window.open(forwardTo, 'itunes');
              },
              error: function (err) {
                console.log('err', err);
                console.log(err);
                window.open('https://itunes.apple.com/us/', 'itunes');
              }
            });
          });// END itunes link click handler

          $.fn.whatsOn.collapse();

        }).always(function () {
          if (schedule === 'now') {
            setTimeout(builder, 60000);
          }
        }).fail(function () {
          $.errorMessage(elem);
        });

      }// END build plugin function

    });// END return the plugin
  };


  // Expand/collapse episode detail - This widgets allows for you to expand an episode to view it's playlist and episode notes.
  $.fn.whatsOn.collapse = function () {
    $('.playlist-controls').on('click.whatsOn', function () {
      $(this).toggleClass('opener');
      $(this).parent().find('.dailyPlaylist').toggle();
    });
    $('.notes-controls').on('click.whatsOn', function () {
      $(this).toggleClass('opener');
      $(this).parent().find('.episodeNotes').toggle();
    });
  };


  // Construct header and setup events handler for the next/previous link
  $.fn.whatsOn.header = function (elem, date, options) {
    var nav_control_prev = '<td class="whatson-prev arrow-left"><a class="hidden" href="#">Previous</a></td>';
    var nav_control_next = '<td class="whatson-next arrow-right"><a class="hidden" href="#">Next</a></td>';
    var header_nav = [
      '<table id="whatson-header" width="100%" border="0" cellspacing="0" cellpadding="0">',
        '<tr>' + nav_control_prev + '<td class="whatson-date">' + date + '</td>' + nav_control_next + '</tr>',
      '</table>'
    ].join('');
    elem.prepend(header_nav);

    // Events handler for navigational next/previous links
    $(elem).find('.whatson-prev, .whatson-next').on('click', options, $.fn.whatsOn.nav);
  };


  // This is the event handler for the widget's next/previous links
  $.fn.whatsOn.nav = function (e) {// BEGIN next/previous date/date-range handler

    e.preventDefault();

    var widget = e.data.elem;
    var header = '.whatson-header';
    var date_header = '.whatson-date';
    var content = '.whatson-content';
    var direction = ( $(e.currentTarget).is('.whatson-next') ) ? 'next' : 'prev';
    var current_date = widget.find(date_header).text();
    var moment_date = moment(current_date, 'dddd, MMMM D YYYY');
    var station = e.data.station;
    var schedule = e.data.schedule;
    var affiliates = e.data.affiliates;
    var full_week_date = current_date.replace('Week of ', '');
    var request_url;
    var options = {}; // Configuration

    // Configure buy links for songs within episodes
    if (affiliates.itunes) options.itunes = affiliates.itunes;
    if (affiliates.amazon) options.amazon = affiliates.amazon;
    if (affiliates.arkiv) options.arkiv = affiliates.arkiv;
    if (e.data.hide_itunes) options.hide_itunes = e.data.hide_itunes;
    if (e.data.hide_amazon) options.hide_amazon = e.data.hide_amazon;
    if (e.data.hide_arkiv)  options.hide_arkiv = e.data.hide_arkiv;

    if (e.data.show_song) options.show_song = e.data.show_song;// Display song meta data

    if (e.data.style) options.style = e.data.style;// Which template is being used


    // This function updates the display after a new request is made
    var updater = function (request_url, update_header) {

      $('.opener, .closer').off('.whatsOn'); // Disable event handlers

      $.when( $.template(request_url) ).done( function (data) { // After the request, update the display
        widget.find(header)
          .remove().end()
          .find(date_header).html(update_header).end()
          .find(content).replaceWith(data);

        $.fn.whatsOn.collapse();
      });

    };

    if (direction === 'next') { // The 'next' link was clicked

      var next_from_current = moment(full_week_date, 'MMMM D YYYY').add('d', 7);

      // Set the next date/date-range.  If its the daily widget use a date, for the weekly widget use a range
      var next_api = ( schedule === 'week' )
        ? '?date=' + next_from_current.isoday(1).format('YYYY-MM-DD')
        + ',' + next_from_current.isoday(7).format('YYYY-MM-DD')
        : '?date=' + moment_date.add('d', 1).format('YYYY-MM-DD');
      var next_header = ( schedule === 'week' )
        ? moment(next_from_current, 'MMMM D YYYY').isoday(1).format('[Week of] MMMM Do, YYYY')
        : moment_date.format('dddd, MMMM Do, YYYY');

      request_url = $.fn.whatsOn.env + '/widget/' + station + '/' + schedule + next_api;

      $.template.params = $.extend({ format: 'jsonp' }, options);

      updater(request_url, next_header);// Go ahead and update the display to be the 'next' date/date-range

    } else {

      // Set the previous date/date-range.  If its the daily widget use a date, for the weekly widget use a range
      var prev_from_current = moment(full_week_date, 'MMMM D YYYY').subtract('d', 7);
      var prev_api = ( schedule === 'week' )
        ? '?date=' + prev_from_current.isoday(1).format('YYYY-MM-DD')
        + ',' + prev_from_current.isoday(7).format('YYYY-MM-DD')
        : '?date=' + moment_date.subtract('d', 1).format('YYYY-MM-DD');
      var prev_header = ( schedule === 'week' )
        ? moment(prev_from_current, 'MMMM D YYYY').isoday(1).format('[Week of] MMMM Do, YYYY')
        : moment_date.format('dddd, MMMM Do, YYYY');

      $.template.params = $.extend({ format: 'jsonp' }, options);

      request_url = $.fn.whatsOn.env + '/widget/' + station + '/' + schedule + prev_api;

      updater(request_url, prev_header);// Go ahead and update the display to be the 'previous' date/date-range
    }

  };// END next/previous date/date-range handler

  // Default widget options
  $.fn.whatsOn.options = {
    schedule: 'now',
    label: true,
    env: 'https://api.composer.nprstations.org/v1',
    assets: 'https://composer.nprstations.org',
    affiliate: {},
    times: true,
    next: true
  };

  // === End .whatsOn plugin functions ===

})(jQuery, window, document);
...