如何将html放入js循环中

How to put html into js loop

本文关键字:js 循环 放入 html      更新时间:2023-09-26

今天我需要关于如何使用html代码进行循环并在输入名称上输入(I)值的帮助:

    <label>
       <input type='radio' class='parts' value='5' /> 5
    </label>
    <script>
    $(function(){
      jQuery('.parts').on('click', function(){
        var html = '';  
        for(i=1; i <= $(this).val(); i++ ){
          html += "<input type='text' name='cars[i]' /> car number i";
        }
        $('#result').html(html);
      });
    });
    </script>
<div id='result'></div>

如果你不明白,请问。

您可以使用字符串串联:

html += "<input type='text' name='cars[" + i + "]' /> car number " + i;

    $(function(){
      jQuery('.parts').on('click', function(){
        var html = '';  
        for(i=1; i <= $(this).val(); i++ ){
          html += "<input type='text' name='cars[" + i + "]' /> car number " + i + "<br>";
        }
        $('#result').html(html);
      });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
       <input type='radio' class='parts' value='5' /> 5
    </label>
<div id='result'></div>