2015-07-28 161 views
-2

我正在尝试开发自己的进度条。此时,我想单击按钮时更新我的​​进度条。我已将一个变量分配给一个函数,该函数在点击按钮时被调用。在JQuery中为变量分配函数

应用程序不能正常运行,因为该函数返回一个对象,我需要一个整数。我试图做出转换,但我不能。这是代码:

<head> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
    <script> 
     $(document).ready(function() {  
      var val = $('#boton').click(function() { 
       return Number(Math.floor(Math.random() * 100 + 1)); 
      }); 
      $("#porcentaje").text(val + '%'); 
      $('#progressBar div').css("width", val.toString() + "%");   
     }); 
    </script> 
</head> 
<body> 
    <form id="formulario"> 
     <div id="progressBar"> 
      <div></div> 
     </div> 
     <div id="porcentaje"> 
     </div>  
     <input type="button" id="boton" value="Start" /> 
    </form> 
</body> 

enter image description here

我怎样才能解决呢?

谢谢。

+0

'parseInt函数(X,10);'? – birdspider

+1

您的变量“val”是您分配给按钮的单击事件的函数,而不是函数返回的值。我想你需要学习更多关于javascript的函数......看看Shomz的答案。 – Kamelkent

回答

1

val是不是你认为在这种情况下的代码。 .click()方法返回对jQuery选择器对象的引用,这就是为什么你没有得到数字值。看到这一点:

$(document).ready(function() { 
 
    var val = 0; 
 
    $('#boton').click(function() { 
 
    val = Number(Math.floor(Math.random() * 100 + 1)); 
 
    $("#porcentaje").text(val + '%'); 
 
    $('#progressBar div').css("width", val.toString() + "%"); 
 
    }); 
 
    setInterval(function(){ 
 
    alert("Val is currently: " + val); 
 
    }, 5000); 
 
});
#progressBar div {height: 10px; background: #eee; width: 0}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form id="formulario"> 
 
    <div id="progressBar"> 
 
    <div></div> 
 
    </div> 
 
    <div id="porcentaje"> 
 
    </div> 
 
    <input type="button" id="boton" value="Start" /> 
 
</form>

+0

之内。起初,我的代码就像你写的那样。这个代码的问题是,除了点击按钮的时刻,val始终为0,并且我希望将val的值存储在点击按钮函数之外。 – user2656997

+0

我的例子*确实*存储了点击回调函数外的val。你在做什么?我已经更新了我的答案,以便您可以每5秒钟在警报中看到'val'的实际值。 – Shomz

1

.click()将返回调用它的相同jQuery对象,这就是为什么你得到Object作为输出。

相反,你只是需要移动这台事件处理程序中的文本和CSS像

$(document).ready(function() { 
 
    var val; 
 
    $('#boton').click(function() { 
 
    val = Number(Math.floor(Math.random() * 100 + 1)); 
 
    $("#porcentaje").text(val + '%'); 
 
    $('#progressBar div').css("width", val + "%"); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<form id="formulario"> 
 
    <div id="progressBar"> 
 
    <div></div> 
 
    </div> 
 
    <div id="porcentaje"> 
 
    </div> 
 
    <input type="button" id="boton" value="Start" /> 
 
</form>

+0

http://jsfiddle.net/arunpjohny/1s6r4f2L/ –

+0

起初,我的代码就像你写的。这个代码的问题是,除了点击按钮的时刻,val始终为0,并且我希望将val的值存储在点击按钮函数之外。 – user2656997

+0

@ user2656997然后只是让'val'成为一个闭包变量,而不是将其作为本地变量......然后在'val'的dom就绪处理函数值中将会改变.... –