这是场景。在jQuery DataTable中,我有一些价值和编辑按钮来修改其中的2个;点击它,一个模式弹出打开,提供了一种形式来插入注释和状态的新值:如何将变量选择器传递给jquery .attr()
...
"columnDefs": [
{
"targets": [ 0 ],
"visible": false
//"searchable": false
}],
"columns": [
{ "data": "id" },
{ "data": "date" },
{ "data": "type" },
{ "data": "name" },
{ "data": "user_name" },
{ "data": "status" },
{ "data": "closing_date" },
{ "data": "info" },
{ "data": "note" },
{ "data": null,
"render": function (data, type, full, meta) {
return "<button type='button' class='btn btn-info btn-md' id=\'" + full.id + "\' data-toggle='modal' data-id=\'" + full.id + "\' data-target='#myModal'> Edit </button>";
}
...
正下方,我有ajax函数将插入的值发送到Spring控制器:
//This function is used to send the form data to Spring controller; cause we use a modal, with code that must be put in the file with html table head,
//we must replace the use of view made by jsp using an ajax function
$('#myModal').on('click', '.btn.btn-success', function(event) {
var form = $('#updateeventsform'); //recover the form inside modal by using id
var formdata = form.serializeObject(); //use the serializeObject function to prepare data for Json format
formdata.idevent = $(this).attr('data-id'); //add the event id to form data, after setting it with the IDnumber variabile
console.log(formdata, this);
event.preventDefault();
//here starts the code to sending data to Spring controller
$.ajax({
url: "../updateevents.json",
type: "post",
data: formdata,
success : function() {
console.log("Invio riuscito.");
DTevents.ajax.reload(null, false); //we reload the table, showing immediately the data updated.
}
});
});
此代码给了我一个未定义的值formdata.idevent;这是正确的,因为$(this)
值引用当前元素(在我的情况下,提交按钮)。 正如您所看到的,该按钮的ID是一个数字值,由full.id
字段设置。 所以,我试了一下:把一个数字值作为attr()
函数的选择器。我改变:
formdata.idevent = $(this).attr('data-id');
在
formdata.idevent = $('#5').attr('data-id');
和工作原理。
所以,问题是:是否有一种方法使用selector
作为.attr()
函数的变量值?如果不是,我应该使用什么将正确的值传递给控制器?
编辑评论答案。
已使用$(this).data('id');不起作用。我为idevent得到了未定义的值。
<button type='button' class='btn btn-info btn-md' **id=\'" + full.id +**
这里你可以注意到button元素的数字id。
意图是:此表代表事件。当修改了2个字段,注释和状态,必须发送给控制器,我必须发送事件ID给它,我想使用.attr()
函数执行此操作。 现在,这个功能必须在选择器上使用;我可能想使用按钮ID作为选择器,但我有不同的按钮与不同的ID。所以,如果我点击第四按钮,id为4,我可能有:
formdata.idevent = $['#4'].attr('data-id');
如果我点击了5按钮的代码必须是:
formdata.idevent = $['#5'].attr('data-id');
如果我点击第六届按钮:
formdata.idevent = $['#6'].attr('data-id');
等等。所以,我有一个变量选择器使用;我不知道如何执行此操作。
难道你不能只格式化一个字符串作为选择器?我知道一个字符串作为变量作为选择器(例如#test_1) – selten98
尝试使用'$(this).data('id');'。在你的例子中'$(this)'指的是'#myModal'而不是'#5' –
不确定你在问什么,但它看起来像你想要的:'var sel =“#5”; var id = $(sel).data(“id”);' –