Jquery事件处理程序上的字符串插值不起作用

时间:2017-07-03 05:52:14

标签: javascript jquery ruby iteration string-interpolation

我在SO和互联网上搜索过,无法找到解决此问题的可行解决方案。本质上,我有一个返回Ruby对象数组的JSON .get请求。然后,我迭代这些对象并将它们放入然后插入DOM中。但是,我尝试将.on click事件处理程序附加到每个li上,尽管我尝试了字符串,但不会插入jquery对象并附加事件处理程序:

function getPrevious(data) { 
   var gamesDiv = '' 
 $.get("/games", function(data) { 
data.data.forEach(function(game) { 
gamesDiv += $(`<li class="game" data-id="${game.id}"> ${game.id} ${game.attributes.state} \n </li>`).on("click", function (e) {

  alert("hello")
 }); 
   $("#games").html(gamesDiv) 
 }); 
}

目前的化身甚至都没有在DOM中显示出来。在其他方面,我已经显示了它,但只显示为[object object] [object object]而没有附加事件处理程序。

我一直试图让这个工作几个小时,所以如果有任何人可以提供任何见解,我将非常感激!

1 个答案:

答案 0 :(得分:1)

您不能将jQuery对象视为字符串,这是导致错误显示在代码中的主要原因,因为您尝试将gameDivjQuery连接起来{1}}对象。

您可以在每个游戏数据中使用Array#map来简化此操作,返回代表列表的jQuery实例(这还包括注册事件处理程序等)。

将游戏列表转换为<li> jQuery个实例的数组后,您可以用转换后的数组替换#games元素的内容。

function getPrevious(data) {
  $.get('/games', function(data) {
    var list = data.data.map(function(game) {
      return $(
        `<li class="game" data-id="${game.id}">
        ${game.id} ${game.attributes.state} \n
        </li>`
      ).on('click', function() {
        alert(JSON.stringify(game, 0, 4));
      });
    });
    $('#games').html(list);
  });
}

&#13;
&#13;
// This mocks the $.get function, to provide controlled result
$.get = function(route, callback) {
  return callback({
    data: [
      { id: 1, attributes: { state: 'State 1' } },
      { id: 1, attributes: { state: 'State 2' } },
      { id: 1, attributes: { state: 'State 3' } }
    ]
  });
};
// Do not include the code above in your code base

function getPrevious(data) {
  $.get('/games', function(data) {
    var list = data.data.map(function(game) {
      return $(
        `<li class="game" data-id="${game.id}">
        ${game.id} ${game.attributes.state} \n
        </li>`
      ).on('click', function() {
        alert(JSON.stringify(game, 0, 4));
      });
    });
    $('#games').html(list);
  });
}

getPrevious();
&#13;
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>


<ul id="games">

</ul>
&#13;
&#13;
&#13;