簡體   English   中英

使用 jQuery 增加輸入字段值

[英]Increment input field value with jQuery

我希望每次當用戶輸入數字時,在控制台中打印新的 + 舊的

這是 html 腳本

 <input type="number"value=""/>
 <button>click</button>

我的jQuery代碼

$("button").click(function (){
    var x = $("input").val();
    x+=x;
    console.log(x);
});

您必須在某處外部初始化值以保持其狀態。

HTML

<input type="number" id="inp" value=""/>
<button>click</button>

JS

var x = 0;

$("button").click(function (){
    var y = parseInt($("#inp").val());
    x+=y;
    console.log(x);
});

希望這對你有所幫助。 參考工作演示。

 var thevalue = 0; $("#click").click(function(){ $("#display").text("The Value is :"); var theinput_value = parseInt($("#num").val()); thevalue += theinput_value; $("#display").append(thevalue); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> Enter the nubmer : <input type="number" id="num"><button id="click">Click on me !</button> <br> <p id="display">The Value is :</p> 

您好,歡迎來到stackoverflow社區。

您正在嘗試將輸入添加到變量x ,但是第一次執行代碼時, x值為“”,即空字符串。

基本上你說的是,嘿javascript,什么是5+“”?

如果你運行console.log(typeof (""+5)); 輸出是string 這意味着你打算得到一個數字,最后得到一個字符串,因為沒有初始化x

此外, x在點擊功能的范圍內定義。 這意味着在執行該函數后根本沒有x ,因此當您再次單擊並再次執行該函數時,將再次創建x

為了解決這個問題,只需在函數范圍之外聲明x

 var x = 0; $("button").click(function (){ // get the input value of the box var input_value = $("input").val(); // parse the value to an integer var number = parseInt(input_value) || 0; // add it to the existing value of x x = x + number; // show the results console.log(x + ' - ' + typeof x); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="number" value=""/> <button>click</button> 

您只需要確保x是一個全局變量,這樣您就可以保存它的值,並在每次觸發單擊處理程序時使用。

我使用添加賦值運算符時添加了輸入轉換以避免字符串連接。

var x = 0;     
$("button").click(function (){
     // Get the input
      var current_input = parseInt($("input").val());
     // If input is not a number set it to 0
      if (isNaN(current_input)) current_input = 0;
     // Add the input to x
      x+=current_input;
     // Display it
      console.log(x);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM