如何使数字自动使用jquery追加

How to make the numbers automatically using jquery append ..?

本文关键字:jquery 追加 何使 数字      更新时间:2023-09-26

大家好,我想问一下,如何使数字自动使用jquery追加…?我成功了,但还是失败了我的源代码是:

<html>
<head>
    <title>Help Help</title>
</head>
<body>
    <input type="button" id="button" value="Create a number from 1 to N"/>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function ()
        {
            $('#button').click(function()
            {
                $('#result').append('<div class="number">Numbers To ......</div>');
            });
        });
    </script>
</body>
<hr>
results from click button
<hr>
<div id=result></div>

有一种方法:

$('#numbers').change(
    function(){
        var max = $(this).val();
        var sequence;
        for(i=0; i<=max; i++) {
            var text = $('#result').text();
            if (text == false){
                text = i;
            }
            else if (i == max) {
                text = text + ', ' + i + '.';
            }
            else {
                text = text + ', ' + i;
            }
            $('#result').text(text);
        }
    });
$('form').submit(
    function(){
        return false;
    });

用下面简化的html:

<form action="#" method="post">
    <label for="numbers">Make a sequence of numbers, from one to <em>n</em></label>
    <input type="number" min="0" max="1000" step="1" id="numbers" name="numbers" />
</form>
<div id="result">
</div>

JS Fiddle demo.


编辑以提供上述jQuery代码的更简洁的版本,由mplungjan提供(在下面的注释中):

$('#numbers').change(
    function(){
        var max = $(this).val(),text="";
        for(i=1; i<=max; i++) {
            text += ', ' + i;
        }
        if(text) $('#result').text(text.substring(2)+".");
    });
$('form').submit(
    function(){
        return false;
    });

修改/优化jQuery在JS Fiddle

答案转换为社区维基,因为从别人的努力中获得代表似乎是错误的....