JavaScript KeyUp() 事件超过个位数

发布于 2025-01-10 22:07:24 字数 1247 浏览 1 评论 0原文

我正在构建这个简单的 JavaScript 项目,如果我输入数字 N,它将显示 1 到 N。我为此使用 keyup() 事件。如果我从输入字段中删除 N,那么它将什么也不显示,这很好!因为我正在使用 empty() 函数。适用于 1-9。但是当我输入 10, 11, 12...时,它首先显示 1,然后相应地显示 1 到 10 或 1 到 11。我只需要看到 1 到 N(超过个位数)。我不想为此使用按钮。

这是我的代码:

$(document).ready(function() {
  $('#code').keyup(function() {
    let myCode = $('#code').val();

    if (myCode == '') {
      $('#output').empty();
    }
    for (let i = 1; i <= myCode; i++) {
      $('#output').append(i + '<br>');
    }
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <input type="number" id="code">
  <br>
  <br>
  <div id="output"></div>
</body>

</html>

如果这个问题有更好的解决办法欢迎分享。

I'm building this simple JavaScript project where if I input number N then it will show 1 to N. I'm using keyup() event for this. If I remove N from the input field then It will show nothing, which is fine! Because I'm using the empty() function. It works for 1-9. But when I input 10, 11, 12... it first shows 1 then it shows 1 to 10 or 1 to 11 accordingly. I only need to see 1 to N(more than single-digit). I don't want to use button for this.

Here is my code:

$(document).ready(function() {
  $('#code').keyup(function() {
    let myCode = $('#code').val();

    if (myCode == '') {
      $('#output').empty();
    }
    for (let i = 1; i <= myCode; i++) {
      $('#output').append(i + '<br>');
    }
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <input type="number" id="code">
  <br>
  <br>
  <div id="output"></div>
</body>

</html>

If this problem has better solution kindly share.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

吾家有女初长成 2025-01-17 22:07:24

您需要使用 setTimeout 来使用去抖动的概念。
您的事件被触发两次,一次是当您按“1”时,一次是当您按“0”时。您需要保持事件直到输入完数字为止。下面的代码可以工作

var timer;
    $(document).ready(function() {
  $('#code').keyup(function() {
      clearTimeout(timer)
      timer = setTimeout(function(){let myCode = $('#code').val();

if (myCode == '') {
  $('#output').empty();
}
for (let i = 1; i <= myCode; i++) {
  $('#output').append(i + '<br>');
}},1000)
    
  })
}); 

You need to use the concept of debouncing using setTimeout.
Your event is getting fired twice, once when you press '1' and when you press '0'. You need to hold the event until you are done with entering the numbers. The below code would work

var timer;
    $(document).ready(function() {
  $('#code').keyup(function() {
      clearTimeout(timer)
      timer = setTimeout(function(){let myCode = $('#code').val();

if (myCode == '') {
  $('#output').empty();
}
for (let i = 1; i <= myCode; i++) {
  $('#output').append(i + '<br>');
}},1000)
    
  })
}); 
何以畏孤独 2025-01-17 22:07:24

正如 Barmar 在评论中指出的那样,每次触发事件时都需要重置输出。
keyup 事件在释放键盘按键后立即发生。
因此,您输入的每个数字都会执行您的侦听器功能(在释放按键后)。

因此,如果您插入 155,它首先会将数字附加到 1-1,然后从 1-15 附加数字(因为当您键入第二个数字并释放按键(事件触发)时,您的输入包含 15),最后一个数字将打印从 1- 到当前输入值 155(输入包含 155)的数字,如果添加数字,依此类推。

因此,您的代码将是:

$(document).ready(function () {
        $('#code').on('keyup', function () {
            let myCode = $('#code').val();
            // when event happens reset the output field, so it is overridden with the new serie
            $('#output').empty();     
                                    
            for (let i = 1; i <= myCode; i++) {
                $('#output').append(`${i}<br>`);                    
            }                            
        });
    });

小建议

对输出使用“缓冲区”,因为每次循环调用追加方法有点昂贵。最好将字符串分开构建,并在完成后将其附加。
使用input事件,它更语义化并且与input标签相关。并且只要输入内容发生变化就会触发该事件,因此更加即时。

$(document).ready(function () {
        $('#code').on('input', function () {
            let myCode = $('#code').val();
            $('#output').empty();     
                                    
            let string = '';            
            for (let i = 1; i <= myCode; i++) {
                string += `${i}<br>`;
            }
            $('#output').append(string);                            
        });
    });

As Barmar pointed out in the comments, you need to reset the output every time the event is fired.
The keyup event happens immediately after the release a keyboard key.
So your listener function is executed every digit you enter (after the release of the key).

So if you insert 155, it first will append number to 1-1, then from 1-15 (because when you type the second digit and release the key (event fired) your input contains 15), and at last digit it will print number from 1- to the current input value that is 155 (input contains 155) and so on if you add digits.

Thus your code would be:

$(document).ready(function () {
        $('#code').on('keyup', function () {
            let myCode = $('#code').val();
            // when event happens reset the output field, so it is overridden with the new serie
            $('#output').empty();     
                                    
            for (let i = 1; i <= myCode; i++) {
                $('#output').append(`${i}<br>`);                    
            }                            
        });
    });

Small suggestions:

Use a "buffer" for the output because the append method is a bit expensive to call every cycle. Better build the string apart and append it when you're done.
Use the input event, it's more semantic and related to input tag. And the event is fired whenever the input content change, so it's more immediate.

$(document).ready(function () {
        $('#code').on('input', function () {
            let myCode = $('#code').val();
            $('#output').empty();     
                                    
            let string = '';            
            for (let i = 1; i <= myCode; i++) {
                string += `${i}<br>`;
            }
            $('#output').append(string);                            
        });
    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文