You guys mind checking out this jsfiddle I made to help you understand my issue. http://jsfiddle.net/kr1zmo/DqbeX/8/:
<a href="#" class="cref">item</a>
<a href="#" class="cref">item 2</a>
<a href="#" class="cref">item 3</a>
<a href="#" class="cref">item 4</a>
<p id="result"></p>
<script language="javascript" type="text/javascript">
(function($) {
$.fn.liveBindTest = function() {
return this['live']('click', function() {
var savedvar;
if (!savedvar || savedvar == 0) {
// is false, do false things.
savedvar = 1;
jQuery('#result').append(savedvar);
} else {
// is true, do true things.
jQuery('#result').append(savedvar);
savedvar = 0;
}
开发者_JAVA百科 return false;
});
};
})(jQuery);
jQuery(document).ready(function() {
$('a.cref').liveBindTest();
});
</script>
I want to save a variable for each click.
Take a look at this example.
Did you want to toggle which bit of code to execute? If you want to hold the value in a closure, you'll need to declare it outside of the live event handler function.
If the value needs to be held for each element matched by the selector, then you could use $(elem).data()
to store the value like in this example.
You declared your variable inside the event handler, creating a separate local variable for each handler.
You need to declare the variable outside the function.
If you want a separate variable for each element, you can declare the variable and add the handler in an each
call, or use jQuery's .data
function.
精彩评论