SyntaxError: 当尝试将对象参数传递给 onclick 函数时,元素列表后缺少 ]

MC *_*C X 4 html javascript jquery

我正在尝试迭代对象列表,并使用按钮为每个对象创建一个列表项。当我onclick给它们添加功能时。我收到这个错误:

语法错误:元素列表后缺少 ]

这是我的代码:

box_resources.forEach(function(box){
    $("#box-resources-list").append('<li><button type="button" class="list-group-item" onclick="showBoxMarker(' + box + ')">' + box.title + '</button></li>');
});
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?谢谢!

Mik*_*uck 5

问题是,box当您创建这样的元素时,它会转换为字符串。例如:

var box = {
  x: 10,
  y: 10,
  w: 5,
  h: 3
};
console.log('onclick="showBoxMarker(' + box + ')"');
Run Code Online (Sandbox Code Playgroud)

显然,调用showBoxMarker([object Object])不是有效的语法。相反,您应该单独创建元素,然后将事件处理程序附加到该元素。

box_resources.forEach(function(box){
    var $listItem = $('<li><button type="button" class="list-group-item">' + box.title + '</button></li>');

    // Find the button we just made and attach the click handler
    $listItem.find('button').click(function() {
        showBoxMarker(box);
    });
    $('#box-resources-list').append($listItem);
});
Run Code Online (Sandbox Code Playgroud)

工作示例:

box_resources.forEach(function(box){
    var $listItem = $('<li><button type="button" class="list-group-item">' + box.title + '</button></li>');

    // Find the button we just made and attach the click handler
    $listItem.find('button').click(function() {
        showBoxMarker(box);
    });
    $('#box-resources-list').append($listItem);
});
Run Code Online (Sandbox Code Playgroud)
var showBoxMarker = function(box) {
  alert(box.title);
}

var box_resources = [
  { title: 'Box A' },
  { title: 'Box B' },
  { title: 'Box C' },
  { title: 'Box D' },
  { title: 'Box E' }
];

box_resources.forEach(function(box){
  var $listItem = $('<li><button type="button" class="list-group-item">' + box.title + '</button></li>');

  // Find the button we just made and attach the click handler
  $listItem.find('button').click(function() {
    showBoxMarker(box);
  });
  $('#box-resources-list').append($listItem);
});
Run Code Online (Sandbox Code Playgroud)

专业提示:一般来说,最好从某种模板而不是 JS 中的字符串创建新元素,并在父元素上创建一个单击处理程序,并使用事件委托来处理各个元素上的单击事件。