[英]Function stored in a global variable doesn't run when called
我是一个菜鸟,也是这个网站的新手,所以如果我应该做些什么来改进这篇文章,请告诉我。 无论如何,我有一个在我的站点中经常重复使用的函数,所以我将它存储在一个全局变量中,并希望在单击某个按钮时调用它。
代码如下所示(见下文)。 我的问题是,虽然我可以确认按钮单击尝试调用该函数,但它显然从未真正被调用过(我的警报均未触发,对文本字段的更改未保存)。 所有这些都包含在$(document).read(function...
我是不是在某个地方犯了一个愚蠢的错误,或者我做错了什么?
$(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 delimiter
//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, delimited 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(具有相同的内部结构)并且工作正常,所以我必须在我之前的一行代码中有一些不寻常的东西。
感谢您的建议!
尝试设置window.Global = ...
,因为声明var Global
将范围设置在就绪闭包内。
然后你应该可以稍后使用它。
我刚刚删除了全局变量并为 saveAll() 创建了一个单独的函数,它可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.