从Datatables.js插件内部动态构建bootstrap 4模式链接



我正在使用Datatables.js-jquery插件来构建html表(jquery 3.2.1版);数据表生成的html表还需要有一个列单元格(author_id)作为可点击的链接,该链接打开bootstrap 4模式,并将author_id的唯一id传递给该模式。

我能够(有点)生成具有所有属性的href标记,并能够打开模态,但由于某种原因,在我执行console.log时,在DataTable初始化函数中生成的id(author_id)会被多次显示(我在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引导模式中的href标记-我尝试了以下代码,但没有定义(当我尝试检索数据id的值时:

var mypostid = $("#mymodal").data('id');
console.log( mypostid );
//GETTING ERROR HERE

如何检索传递给modal的数据id(它是唯一的author_id),并显示基于数据id的各种输入字段?

在您的示例中,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文档提供了更多信息。

最新更新