我是一个菜鸟,也是这个网站的新手,所以让我知道我是否应该做些什么来改进这个帖子。无论如何,我有一个在我的网站中经常重复使用的函数,所以我将它存储在一个全局变量中,并希望在单击某个按钮时调用它。代码看起来像这样(见下文)。我的问题是虽然我可以确认按钮点击试图调用该函数,但显然从未实际调用过(我的警报都没有触发,并且没有保存对文本字段的更改)。所有这些都包含在$(文件).read中(功能......我在某个地方犯了一个愚蠢的错误,还是我做错了什么?
$(document).ready(function () {
//Description:
//Global wrapper variable that contains all global functions. These include:
// 1. saveAll: Saves all values not stored in session data to hidden fields - this includes
// all added ingredient information. This allows us to manually pass values between
// client and server to save to db and also means we can eliminate Null values in table
// storage using a manual delimiter.
//----------------------------------------------------------------------------------------------
var Global = (function () {
return {
saveAll: function () {
alert("entering save");
//start by creating an array and initializing the length of the for loop
var saveValues = [];
var numVals = $('#HidRowCt').val();
alert("numVals: " + numVals);
//Now loop through each ingredient row and create a string containing all textbox values
//in this case, we'll do so by creating an array and then combining the values with a custom delimeter
//the strings will then be saved, one by one, into the saveValues array, which will be serialized as a JSON object,
//stored in a hidden field, and passed to the server
for (i = 1; i < numVals; i++) {
var TxtIngName = $('#TxtIngName' + i).val();
var TxtIngNumUnits = $('#TxtIngNumUnits' + i).val();
var SelIngUnits = $('#SelIngUnits' + i).val();
//make temporary array and string
var saveArr = new Array(TxtIngName, TxtIngNumUnits, SelIngUnits);
var saveStr = saveArr.join("-||-");
saveValues.push(saveStr);
}
alert("Save Values: " + saveValues);
//this will automatically escape quotes, delimmited with ","
var jsoncvt = JSON.stringify(saveValues);
$("#HidSave").val(jsoncvt);
}
};
});
//----------------------------------------------------------------------------------------------
//Description:
//Hijack the click event for the save button. Saves values not saved in session data.
//
//Functions:
// Global.saveAll()
//----------------------------------------------------------------------------------------------
$("#SaveChanges").data.clickEvent = $("#SaveChanges").attr('onClick'); //save onclick event locally
$("#SaveChanges").removeAttr('onClick'); //and remove the onclick event
$('#SaveChanges').on('click', function (event) {
Global.saveAll();
//eval($("#SaveChanges").data.clickEvent); //now go ahead with the click event
});
**嗯,我从来没有弄清楚为什么这不起作用,但......
我刚删除了全局变量并为saveAll()创建了一个单独的函数,它可以工作。有趣的是,我有第二个应用程序使用相同的代码,使用Global.saveAll(具有相同的内部)并且工作正常,所以我必须在我之前的一行中有一些不寻常的东西。
感谢您的建议!
答案 0 :(得分:0)
尝试设置window.Global = ...
,因为声明var Global
会将范围设置为就绪闭包。
然后你应该可以在以后使用它。
答案 1 :(得分:0)
我刚删除了全局变量并为saveAll()创建了一个单独的函数,它可以工作。