尝试将对象参数传递给onclick函数时,元素列表后出现SyntaxError:缺少] [英] SyntaxError: missing ] after element list when try to pass object parameter to onclick function

查看:57
本文介绍了尝试将对象参数传递给onclick函数时,元素列表后出现SyntaxError:缺少]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to iterate a list of objects, and create a list item for each of them with as a button. When I add onclickfunction to them. I got this error:

SyntaxError:元素列表后缺少]

SyntaxError: missing ] after element list

这是我的代码:

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

有任何想法吗?谢谢!

推荐答案

问题是在创建类似元素时box会转换为字符串.例如:

The problem is that box is converted to a string when you're creating elements like that. For example:

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

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

Obviously, calling showBoxMarker([object Object]) isn't valid syntax. Instead, you should create the elements separately then attach an event handler to that element.

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);
});

工作示例:

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);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="box-resources-list"></ul>

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

Pro-tip: In general, it's better to create new elements from some kind of template instead of from strings in JS and create one click handler on a parent element and use event delegation to handle click events on individual elements.

这篇关于尝试将对象参数传递给onclick函数时,元素列表后出现SyntaxError:缺少]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆