簡體   English   中英

使用 jQuery 進行現場輸入時遞增計數器

[英]Increment counter upon field input with jQuery

我想創建一個聯系表單字段(對用戶不可見),其鏈接的無按鈕計數器在源代碼中填充后立即遞增 1(因此我選擇輸入 function,無論輸入的字符數如何)。 使用輸入值 = 0。如果我測試它(在我的 IDE 預覽網站上的“可見”模式下)並輸入一些內容,之后將阻止表單提交。 計數器工作並顯示“1”。

看這里

如果我刪除我的輸入,單擊它並再次輸入一些內容,它不會進一步增加並且仍然顯示“1”。 這一切都沒有刷新我的頁面,將計數器值存儲在 local.storage 中,我的頁面上一直顯示“1”。

 $("#mail_conf").on("input", function(){ $("#counter").html(function(val){ return val+1; }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="email" id="mail_conf" name="user_email_conf" placeholder="E-mail conf.*"> <div id="counter">0</div>

 $("#mail_conf").on("input", function () { // first arg is index, 2nd is oldhtml. `+val` converts the string to an int $("#counter").html("1") });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="mail_conf"> <p id="counter">0<p>

這能解決您的問題嗎?

我注意到的問題是您正在嘗試將.html()與 function 一起使用,根據文檔,它作為第一個參數index返回, oldhtml作為第二個參數返回。 https://api.jquery.com/html/#html-function

暫無
暫無

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

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