I want to make a jquery function which will be returning a number and I want to use that function somewhere else. please suggest if below is the rigt way of doing it.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function print()
{
var count=1;
$('#forwardbutton').click(function(){
count++;
});
return count;
};
</script>
-
@MohitArora: You can, just not like that. :-)T.J. Crowder– T.J. Crowder2014年08月05日 09:29:07 +00:00Commented Aug 5, 2014 at 9:29
-
Then what is alternative? @MohitAroraVaibhav– Vaibhav2014年08月05日 09:29:20 +00:00Commented Aug 5, 2014 at 9:29
-
You should read this(sitepoint.com/5-ways-declare-functions-jquery)Vikram– Vikram2014年08月05日 09:31:15 +00:00Commented Aug 5, 2014 at 9:31
2 Answers 2
You can't have the print function return the number of times that the element has been clicked. Your print function will only ever return 1.
If you want a function that hooks up a click handler and then does something with the number of times the element has been clicked, you can do it by having the function accept a callback. (I wouldn't call the function print, as there's a global print function already, and that can get confusing really fast.)
For example:
function someNameHere(callback) {
var count = 0;
$('#forwardbutton').click(function(){
++count;
callback(count);
});
}
Then you can use it like this:
someNameHere(function(newCount) {
// ...use `newCount`...
});
Note that the function now accepts a callback function,and calls it each time the element is clicked, with the new click count. (I also started the count at 0 rather than 1.)
Comments
Remove function since you cannot use click event like the way you are doing
Try this :
$(document).ready(function()
{
var count=1;
$('#forwardbutton').click(function(){
count++;
// your code to use count variable
});
});