How to make sure buttons events are only triggered once in Javascript/JQuery?
I'm new to JQuery, and Javascript, and I am using the JQueryUI ProgressBar, and every time somebody clicks on a button, then the progress bar animates and fills up. Is there a way to keep track of which buttons are already pressed to prevent the buttons from triggering the event again?
Current HTML:
<ul>
<li><a href="left/section1.html" target="leftcontainer" onClick="updateBar();window.presentation.location.href='right/section1/page1.html';;return true;">overview</a></li>
<li><a href="left/section2.html" target="leftcontainer" onClick="updateBar();window.pr开发者_StackOverflowesentation.location.href='right/section1/page1.html';;return true;">key features</a></li>
<li><a href="#" onClick="updateBar()">customers</a></li>
<li><a href="#" onClick="updateBar()">accessories</a></li>
<!--<li><a href="#">nav5</a></li>
<li><a href="#">nav6</a></li> -->
</ul>
Current JQuery/JavaScript:
var percentage = 0;
function updateBar()
{
percentage += 25;
$('.ui-progressbar-value').stop().animate({ width: percentage+"%" }, 500)
$('.middle').progressbar('option','value', percentage);
if(percentage > 100)
{
$('ui-progressbar-value').stop().animate({ width: "100%"}, 500);
}
}
$(function() {
$('.middle').progressbar({
value: percentage,
complete: function() { alert('The progress bar is full'); }
});
I would bind the click event in the JavaScript and use the jQuery .one()
method.
documentation
Basically the one method allows you to bind an event that can only be triggered once, such as a click event.
Live Demo
var percentage = 0;
$('ul li a').one('click', updateBar);
function updateBar()
{
percentage += 25;
$('#test').text(percentage);
}
HTML (add a class):
<li><a href="#" class='clickable'>customers</a></li>
<li><a href="#" class='clickable'>accessories</a></li>
JS
var percentage = 0;
$(function() {
$('.clickable').click(function updateBar(){
$(this).unbind('click'); //dont allow click again
percentage += 25;
$('.ui-progressbar-value').stop().animate({ width: percentage+"%" }, 500);
$('.middle').progressbar('option','value', percentage);
if(percentage > 100)
{
$('ui-progressbar-value').stop().animate({ width: "100%"}, 500);
}
});
$('.middle').progressbar({
value: percentage,
complete: function() { alert('The progress bar is full'); }
});
});
精彩评论