I am new in Javascript and made a function structure like this:
var project = ... ; // it's dynamic
// first function
$('body').on('click', '.projectmonitoring', function () {
SetMonitoring(project);
});
// second function
function SetMonitoring(project) {
var tasks = ... ; // this variable produced inside Ajax
// third function
$('#save').click(function () {
// do something using project and tasks variable
});
}
Whenever I called the first function, SetMonitoring function was triggered of course. I called first function more than one (do a click twice or more). When I call the third function, what happens is the third function was executed much as the amount I called first function.
Maybe I am wrong in the structure. I hope has been explained well. Thanks in advance.
Make a global var, set it in second function and then use it in third function.
var value_of_project;
// first function
$('body').on('click', '.projectmonitoring', function () {
SetMonitoring(project);
});
// second function
function SetMonitoring(project) {
//set value of project here
value_of_project = "some value";
}
// third function
$('#save').click(function () {
//do something using value_of_project
});
好吧,您可以使用:$('#save')。off('click')。click(function(){...但是更好的解决方案是收回代码。您无需将项目par传递给setmonitoring如果它是全局函数,则可以使用...但是在任何情况下,在ivent处理程序中附加事件处理程序都是一种反模式...
To make sure your function is being called only once-
use one
-
var project = ... ; // it's dynamic
// first function
$('body').one('click', '.projectmonitoring', function () {
SetMonitoring(project);
});
// second function
function SetMonitoring(project) {
var tasks = ... ; // this variable produced inside Ajax
// third function
$('#save').click(function () {
// do something using project and tasks variable
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.