我正在使用Datatables.js jquery插件来构建html表(jquery版本3.2.1);由数据表生成的html表还需要其中一个列单元格(author_id)是一个可单击的链接,它打开一个bootstrap 4模态,并将author_id的唯一ID传递给模态。
我能够(有点)生成具有所有属性的href标签,并且能够打开模态但由于某种原因,在我的DataTable初始化函数中生成的id(author_id)正在多次显示我做了一个console.log(我在console.log之前放了一个注释,以指示生成倍数的位置)。不知道我做错了什么。以下是我的代码:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "https://sonosfarm.com/prod/authors.cfc?method=Authors",
dataType: "json",
cache: false,
success: function(response){
if(response.length != 0){
$("#authorsHiddenVar").val("");
$("#authorsHiddenVar").val(JSON.stringify(response));
$("#Authors").DataTable({
data: response,
columns:[
{
data: 'author_id',
"render": function(data, type, row, meta){
if(type== 'display'){
data = '<a data-toggle="modal" data-
target="#mymodal" data-backdrop="static" data-keyboard="false"
href="#mymodal" data-id=' + data + '>' + data + '</a>';
}
//THIS IS WHERE THE SAME UNIQUE author_id IS BEING
//SHOWN MULTIPLE TIMES!
console.log(data);
return data;
}
},
{
data: 'joined_date'
},
{data: 'country'}
],
responsive: true,
order: [1, 'desc']
});
}
else{
console.log("There was no response from server!");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log("An Ajax server error was returned");
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
});
我遇到的第二个问题是在mymodal bootstrap模式中解析href标签 - 我尝试了以下代码但是我得到了未定义(当我尝试检索data-id的值时:
var mypostid = $("#mymodal").data('id');
console.log( mypostid );
//GETTING ERROR HERE
如何检索传递给modal的data-id(唯一的author_id),并根据data-id显示各种输入字段?
答案 0 :(得分:1)
在您的示例中,您在data-id
值周围缺少引号(即HTML将呈现为data-id = something而不是data-id =“something”)。
因此,您的数据表init看起来像:
$("#Authors").DataTable({
data: response,
columns:[
{
data: 'author_id',
"render": function(data, type, row, meta){
if(type== 'display'){
return '<a data-toggle="modal" data-target="#mymodal" data-backdrop="static" data-keyboard="false" href="#mymodal" data-id="' + data + '">' + data + '</a>';
}
return data;
}
},
{
data: 'joined_date'
},
{data: 'country'}
],
responsive: true,
order: [1, 'desc']
});
然后,要在你的模态中获取author_id,你需要修改显示模态的jQuery。你没有在你的问题中提供,所以我将给出一个通用的例子:
$('#mymodal').on('show.bs.modal', function (event) {
var link = $(event.relatedTarget) // link that triggered the modal
var author = link.data('id') // Extract info from data-* attributes
var modal = $(this)
modal.find('.modal-title').text('New message to ' + author)
});
来自Bootstrap docs的更多内容。