我用按钮创建表。
以下是javascript代码:
function layersListTable(layers) {
var content ='<table data-role="table" id="layersListEditable" ><thead><tr></tr></thead>';
$.each($(layers), function () {
content += '<tr>';
content += '<td><button data-mini="true" data-inline="true" data-icon="edit" onclick="getProperties(' + this.Id +','+ this.Title + ')" data-theme="b" type="button" >Edit</button></td>';
content += '</tr>';
});
content += '</table>';
return content;
}
该表由javascript创建并附加到DOM。
但是当我点击创建的表格中的按钮时,我收到此错误:
Uncaught SyntaxError: missing ) after argument list
当我从表格中的按钮中删除一个参数(this.Title)时:
function layersListTable(layers) {
var content ='<table data-role="table" id="layersListEditable" ><thead><tr></tr></thead>';
$.each($(layers), function () {
content += '<tr>';
content += '<td><button data-mini="true" data-inline="true" data-icon="edit" onclick="getProperties(' + this.Id +')" data-theme="b" type="button" >Edit</button></td>';
content += '</tr>';
});
content += '</table>';
return content;
}
它的工作enter code here
完美。
知道为什么我上面会出现错误以及如何修复它?
答案 0 :(得分:6)
问题是由于您如何在onclick
属性中附加参数。据推测它们是字符串,因此需要用引号括起来。要做到这一点,你需要绕过它们的单引号,如下所示:
content += '<td><button data-mini="true" data-inline="true" data-icon="edit" onclick="getProperties(\'' + this.Id +'\',\''+ this.Title + '\')" data-theme="b" type="button" >Edit</button></td>';
然而,更好的解决方案是删除过时的on*
事件属性,并通过使用不显眼的事件处理程序完全避免此问题。正如您已经包含jQuery,以下是如何做到这一点:
function layersListTable(layers) {
var content ='<table data-role="table" id="layersListEditable" ><thead><tr></tr></thead>';
$.each($(layers), function () {
content += '<tr>';
content += '<td><button class="edit" data-mini="true" data-inline="true" data-icon="edit" data-id="' + this.Id + '" data-title="' + this.Title + '" data-theme="b" type="button">Edit</button></td>';
content += '</tr>';
});
content += '</table>';
content += '</fieldset>'
return content;
}
$('#layersListEditable').on('click', 'button.edit', function() {
var $btn = $(this);
var id = $btn.data('id');
var title = $btn.data('title');
getProperties(id, title);
});
最后,请注意您的代码缺少<fieldset>
开始标记和<tbody>
包装附加的tr
元素 - 尽管我认为这只是向您转移问题时的错误生产代码。
答案 1 :(得分:1)
这是问题,替换此行肯定会解决您的问题:
content += '<td><button data-mini="true" data-inline="true" data-icon="edit" onclick="getProperties(\'' + this.Id +'\',\''+ this.Title + '\')" data-theme="b" type="button" >Edit</button></td>';