Сценарий jQuery: я заполняю массив, но не могу получить к нему доступ извне - PullRequest
0 голосов
/ 04 ноября 2018

Я начинаю возиться с jquery и схожу с ума ... Я пишу небольшой сценарий для поиска футболистов с сайта фэнтези-футбола. У меня есть следующие HTML и JS для работы:

  <table class="table table-striped">
  <thead>
    <tr>
      <th>Jugador</th>
      <th>Equipo</th>
      <th>Puntos</th>
    </tr>
  </thead>
  <tbody>
    <tr class="jugador">
      <td>Sergio-Ramos</td>
      <td>Real Madrid</td>
      <td></td>
    </tr>
    <tr class="jugador">
      <td>Messi</td>
      <td>F.C. Barcelona</td>
      <td></td>
    </tr>
    <tr class="jugador">
      <td>Morales</td>
      <td>Levante</td>
      <td></td>
    </tr>
    <tr class="jugador">
      <td>Bale</td>
      <td>Real Madrid</td>
      <td></td>
    </tr>
  </tbody>
</table>

И следующий JS:

<script>
  var puntos_jugador = [];

  $(".jugador").each(function(index) {

    var nombre = $(this).find("td").eq(0).text();

    puntos_jugador = puntosJugador(nombre);

    console.log(nombre);
    console.log(puntos_jugador);

    $(this).find("td").eq(2).text("Hola");
  });

  function puntosJugador(nombre) {
    var puntos = [];

    $.get('https://www.comuniazo.com/comunio/jugadores/' + nombre, function(response) {

      $(response).find('.tr-points, .tr-status').each(function(fila) {
        //var jornada = $(this).find("td").eq(0).text();
        var puntos_jornada = $(this).find(".bar").text();
        puntos.push(puntos_jornada);
        //console.log('Jornada ' + jornada + ' ' + puntos);
      });
    });

    return puntos;
  }
</script>

Дело в том, что console.log (puntos_jugador) возвращает массив, заполненный информацией:

enter image description here

Однако я не могу получить доступ к puntos_jugador [0] или попробовать puntos_jugador.toString ().

Может ли кто-нибудь сказать мне, что я делаю неправильно (может быть, все) или дать мне некоторую информацию о том, как это исправить?

Заранее спасибо и извините за мой низкий уровень JS, я работаю над этим.

Ответы [ 2 ]

0 голосов
/ 04 ноября 2018

Проблема в вашем коде заключается в том, что вы делаете асинхронный вызов с $.get, а затем возвращаете результат напрямую, не ожидая ответа, который всегда будет пустым массивом, определенным выше.
Вам следует дождаться ответа, а затем перезвонить (или использовать обещания)

Примерно так:

  var puntos_jugador = [];

  $(".jugador").each(function(index) {

    var nombre = $(this).find("td").eq(0).text();

    puntosJugador(nombre, function(result) {
        console.log('done'); 
        puntos_jugador = result;
        console.log(nombre);
        console.log(puntos_jugador);
    });

    $(this).find("td").eq(2).text("Hola");
  });

  // <---- HERE pass a callback and then call it when you have all results.
  function puntosJugador(nombre, cb) {
    var puntos = [];
    $.get('https://www.comuniazo.com/comunio/jugadores/' + nombre, function(response) {
       console.log('response ',response)
      $(response).find('.tr-points, .tr-status').each(function(fila) {
        //var jornada = $(this).find("td").eq(0).text();
        var puntos_jornada = $(this).find(".bar").text();
        puntos.push(puntos_jornada);
        //console.log('Jornada ' + jornada + ' ' + puntos);
        console.log('here', puntos);
      });
      cb(puntos);
    });
  } 
0 голосов
/ 04 ноября 2018

Измените ваш метод на это:

function puntosJugador(nombre) {
    var puntos = [];

    $.get('https://www.comuniazo.com/comunio/jugadores/' + nombre, function(response) {

      $(response).find('.tr-points, .tr-status').each(function(fila) {
        //var jornada = $(this).find("td").eq(0).text();
        var puntos_jornada = $(this).find(".bar").text();
        puntos.push(puntos_jornada);
        //console.log('Jornada ' + jornada + ' ' + puntos);
      });
      return puntos;
    });


  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...