2013-05-26 71 views
1

我是JQuery的新手,並且正在閱讀有關將數據附加到Jquery對象的內容。我試圖創建一個計時器作爲例子,但無法讓它工作。是關於我使用的JQuery版本嗎?我在網上找到了幾個例子,但不能讓我自己的代碼工作。任何幫助是可觀的。下面是我的代碼:JQuery setData事件

*

<style type="text/css"> 
.progresscont{ 
    width:200px; 
    height:50px; 
    float:left; 
    background-color:#FFFFD5; 
    border:solid 1px #CCC; 
} 
.progress{ 
    background-color:red; 
    width:20px; 
    height:50px; 
} 
.percenttext{ 
    font-weight:bold; 
} 
</style> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
<script language="javascript"> 
$(document).ready(function(){ 
var id=1,i=0; 
//create a div with progress bar and the value 
var progress = $('<div></div>') 
.attr('id','progresscont'+id) 
.addClass('progresscont') 
.append(
    $('<div></div>') 
    .addClass('progress') 
    .append(
     $('<div>0%</div>') 
     .attr('id','percenttext'+id) 
     .addClass('percenttext') 
    ) 
) 
.data('perc','0') 
.bind('setData',function(evt,key,value){ 
    switch(key){ 
    case 'perc': 
    $(this).width(value+'%'); 
    break; 
    } 
} 
) 
.appendTo($(document.body)); 
}); 
function setcounter(val){ 
progress.data('perc',val); 
setTimeout(setcounter(val+1),1000); 
} 
setcounter(0); 
</script> 

*

謝謝

回答

0

沒有一個setData事件,我知道的......也許在一個插件?

無論哪種方式,嘗試這樣的事情(demo):

$(function() { 
    var id = 1, 
     i = 0; 
    //create a div with progress bar and the value 
    var progress = $('<div></div>') 
     .attr('id', 'progresscont' + id) 
     .addClass('progresscont') 
     .data('perc', '0') 
     .appendTo($(document.body)) 
     .append(
      $('<div></div>') 
       .addClass('progress') 
       .append(
        $('<div>0%</div>') 
         .attr('id', 'percenttext' + id) 
         .addClass('percenttext') 
       ) 
     ); 

    function setcounter(val) { 
     if (val > 100) { return; } 
     progress.data('perc', val) 
      .find('.progress') 
      .width(val + '%') 
      .find('.percenttext').text(val + '%') 
     setTimeout(function(){ 
      setcounter(val + 1); 
     }, 50); 
    } 
    setcounter(0); 

}); 
+0

謝謝你的回覆。我的目標是練習使用setData事件。我在JQuery Cookbook中閱讀了它。謝謝 – mrida

+0

也許他們提供它作爲一個插件? – Mottie

0

使用setData事件提供了支持之前的jQuery版本1.8或1.9至。我看到你正在使用v.2.0。