我想将变量从一个函数传递给另一个函数。所以我在第一个函数中定义了变量hello
,然后只想在我的第二个函数中提示它:
var hello;
$(document).ready(function () {
var table = $('#myTable').DataTable();
$('#myTable tbody').on('click', 'td', function () {
var hello = table.cell(this).index().columnVisible;
console.log('Clicked on cell in visible column: ' + hello);
});
table.MakeCellsEditable({
"onUpdate": myCallbackFunction
});
return hello;
});
function myCallbackFunction(updatedCell, updatedRow, oldValue,hello) {
var array = updatedRow.data();
var id = array[0];
var hello;
alert(hello);
console.log("The new value for the cell is: " + updatedCell.data());
console.log("The old value for that cell was: " + oldValue);
console.log("The values for each cell in that row are: " + updatedRow.data());
console.log("The id is: " + id);
jQuery.ajax({
type: "POST",
url: "update.php",
data: {
updatedCell: updatedCell.data(),
id: id
},
cache: false
});
}
我希望3
,因为在我的控制台中,我得到输出Clicked on cell in visible column: 3
,但警报输出为undefined
。
更新:此解决方案仅包含一个var hello
,但警报仍为undefined
var hello;
$(document).ready(function () {
var table = $('#myTable').DataTable();
$('#myTable tbody').on('click', 'td', function () {
hello = table.cell(this).index().columnVisible;
console.log('Clicked on cell in visible column: ' + hello);
});
table.MakeCellsEditable({
"onUpdate": myCallbackFunction
});
return hello;
});
function myCallbackFunction(updatedCell, updatedRow, oldValue,hello) {
var array = updatedRow.data();
var id = array[0];
alert(hello);
console.log("The new value for the cell is: " + updatedCell.data());
console.log("The old value for that cell was: " + oldValue);
console.log("The values for each cell in that row are: " + updatedRow.data());
console.log("The id is: " + id);
jQuery.ajax({
type: "POST",
url: "update.php",
data: {
updatedCell: updatedCell.data(),
id: id
},
cache: false
});
}
答案 0 :(得分:1)
您可以将值存储在DOM中的数据属性中。这样你就不得不混淆全球范围。这是你怎么做的。
将值存储在table
元素中:
//var hello = table.cell(this).index().columnVisible; <<--- REPLACE WITH
$('#myTable').data( 'hello', table.cell(this).index().columnVisible );
从表元素中检索值;
//local variable
var hello = $('#myTable').data('hello');
另一种方法是在DOM准备中定义命名函数,而不是将其定义为全局函数:
$(document).ready(function () {
var hello; //DO NOT redeclare the variable again.
var table = $('#myTable').DataTable();
$('#myTable tbody').on('click', 'td', function () {
hello = table.cell(this).index().columnVisible;
console.log('Clicked on cell in visible column: ' + hello);
});
table.MakeCellsEditable({
"onUpdate": myCallbackFunction
});
function myCallbackFunction(....) {
//......REMEMBER DO NOT USE var in front of hello
}
});
答案 1 :(得分:0)
从var hello;
myCallbackFunction
答案 2 :(得分:0)
从两个函数中删除“hello”变量之前的var
关键字。保持它只是在第一行。如果这不能解决问题,请尝试从hello
删除参数myCallbackFunction
;