2011-08-17 80 views
1

我是JQuery和Javascript的新手,我使用的是JQueryUI ProgressBar,每当有人点击一个按钮时,进度条就会动画并填充。有没有办法跟踪哪些按钮已被按下以防止按钮再次触发事件?如何确保按钮事件只在Javascript/JQuery中触发一次?

当前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.presentation.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> 

当前的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'); }  
    }); 

回答

4

我会结合JavaScript的click事件,并使用jQuery的.one()方法。

documentation

基本上一个方法允许你绑定只能触发一次,如点击事件的事件。

Live Demo

​​
+0

这工作就像一个魅力,简单到如此地步。我将不得不在JQuery文档中进行更多的挖掘。非常感谢! :D – lislis

+0

页面刷新/重新加载后,用户可以再次调用该功能。有什么办法来限制这一点。我在问,因为这个函数在iframe页面被调用,并且当用户点击一个链接时刷新页面,否定一次调用。有任何想法吗? – lislis

+0

如果页面重新加载,JS将被重新加载:?您可以尝试使用参数page.html?perc = 25重新加载页面,因此在重新加载它时知道百分比已经达到25%。或传递通过页面参数点击的元素。然后,您将不得不在网页加载时解析url参数并禁用链接。但这完全是另一个问题。 – Loktar

0

HTML(添加类):

<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'); }  
    }); 
}); 
+0

这个效果很好,除了它限制了我实际上重新点击该按钮的时候,我实际上需要这样做。但是,我喜欢它的一般化,所以它可以应用于任何元素。 – lislis