Keeping variables between function executions (Javascript) -
i have javascript function runs every time 1 of many links clicked. functions first checks id of link clicked is, runs if stement. depending on id of link, different variables defined.
all works, problem links define 1 variable while other links define another, need maintain variables defined in previous executions of function defined other executions of function.
an illustration follows:
$(document).ready(function() { $(".sidebar a").click(function(event) { event.preventdefault() var targetid = $(this).attr("data-target") $("#" + targetid).attr("src", $(this).attr("href")) var element = $(this).attr("class") if (element == "submit") { var submit = $(this).attr("user") alert("1") } else if (element == "view") { var view = $(this).attr("user") alert("2") } }) window.history.replacestate({}, 'logs', '/file/path?submit=' + submit + '&' + 'view=' + view) })
thanks
you can utilize outer function nil declare variables , homecoming inner function. inner function can access variables outer scope remain same every phone call of function.
examplevar next = (function() { var value = 0; function next() { homecoming value++; } }()); console.log(next()); console.log(next()); console.log(next());
live demo http://jsfiddle.net/bikeshedder/uzkte/
javascript variables
No comments:
Post a Comment