创建有序列表并生成输入字段 HTML 和 JS



我在这里拥有我应用和尝试的内容的完整代码。使用下面的JS,我错误地显示了有序列表的显示。它必须在1,2,3 ...中(依次来回)。为此,它坚持使用1.,1.,1. ...。另一个是,使用下面的JS,如何自定义我将获得dynamic输入字段?因为如果我输入5怎么办?字段的结果也必须为5。但是发生了什么事,将5个字段添加/附加到当前字段数(示例,i之前输入3个字段,显示3个字段,因此当输入5个字段时,总共有8个备案)。我想要的是输入数字的确切字段数。(在JS方面不太擅长,但我非常想学习它的本质)。

<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function() {
   $("ul").each(function() {
    $(this).find("li").each(function(count) {
       $(this)
         .css("list-style-type", "none")
         .prepend("<div class='listnumber'>" + (count + 1) + ".</div>");
       });
    });
 })    
</script>
<script type="text/javascript">
  $(document).ready(function() {
  $('[name="cand_no"]').on('change', function() {
         if (this.value != '') {
             var val = parseInt(this.value, 10);
             for (var i = 0; i < val; i++) {
                 var $cloned = $('.template tbody').clone();
                 $('#studentTable tbody').append($cloned.html());
         }
     });
  })
</script>   
</head>
 <body>
      <p>
         <label><strong>No.: </strong></label>
         <label><input name="cand_no" type="number" placeholder="Enter no. of fields." /></label>
         <div class="clear"></div>
     </p>
     <div class="cand_fields">
       <table id="studentTable" width="630" border="0">
            <tr>
               <td>Name</td>
            </tr>
            <tr>
               <td><input name="cand_name" type="text" placeholder="Name" required="required" /></td>
            </tr>
       </table>
    </div>
    <div class="template" style="display: none">
       <table>
        <tr >
           <td><ul><li><input name="cand_name" type="text" placeholder="Name" required="required" /></li></ul></td>

           </tr>
        </table>
      </div>
   </body>
</html>

感谢一百万..

尝试

$(document).ready(function () {
    $(".template ul li").css("list-style-type", "none").prepend("<div class='listnumber'></div>");
})
$(document).ready(function () {
    var $tmpl = $('.template tbody'),
        $target = $('#studentTable tbody');
    $('[name="cand_no"]').on('change', function () {
        if (this.value != '') {
            var val = (parseInt(this.value, 10) || 0) + 2;
            var len = $target.children().length;
            if (val < len) {
                $target.children().slice(val).remove();
            } else {
                for (var i = len; i < val; i++) {
                    $($tmpl.html()).appendTo($target).find('.listnumber').text(i - 1);
                }
            }
        }
    });
})

演示:小提琴

最新更新