简体   繁体   English

jQuery clone()无法按预期工作

[英]Jquery clone() not working as expected

Html code: HTML代码:

<form>
    <table>
        <tr>
            <td>Value</td>
            <td class="to">ABC</td>
        </tr>
    </table>
</form>
<div class="from" style="display:none;">
    <label>
        <input type="text" value="" placeholder="Number"/>
    </label>
</div>

and this javascript code: 和这个JavaScript代码:

$(document).ready(function(){
          var values = [12,11,15];
          var cloned = $('div.from').find('label').clone();
          $('td.to').empty();
          for(var i=0;i<values.length;i++){
              cloned.find('input').val(values[i]);
              //console.log(cloned);
              console.log(cloned.find('input').val());
              $('td.to').append(cloned);
          }
});

I am here trying to clone the nested ' label ' from the hidden div ' div.from ' and set one of the value from the ' values ' array and append to empty ' td.to ' using the same cloned object. 我在这里尝试从隐藏的div.from '中克隆嵌套的' label ',并从' values '数组中设置值之一,并使用相同的克隆对象将其追加到空的' td.to '。 As far as I know, the last value of the array seems to be appended after cloning. 据我所知,数组的最后一个值似乎是在克隆后附加的。 The result should have been three cloned nested labels with value populated in the input box from the ' values ' array. 结果应该是三个克隆的嵌套标签,其值在' values '数组的输入框中填充。

Here is jsbin link : http://jsbin.com/yuyaqu 这是jsbin链接: http ://jsbin.com/yuyaqu

You need to clone() once per iteration, so put that line within the for : 您需要每次迭代一次clone() ,因此将该行放入for

var values = [12,11,15];
$('td.to').empty();
for (var i = 0; i < values.length; i++){
    var cloned = $('div.from').find('label').clone();
    cloned.find('input').val(values[i]);
    $('td.to').append(cloned);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM