2011-04-19 46 views
0

我有一个SELECT,我选择用户有多少辆汽车。之后,他/她将获得与INPUT相同数量的DIV来描述模型等。jQuery:克隆元素通过选择SELECT OPTION

如何使用SELECT来克隆包含INPUT的DIV?

+0

请分享一些代码。或者至少给jsfiddle一个链接。 – 2011-04-19 09:24:09

回答

0

这应该给你的总体思路...

$('select#cars').change(function() { 
    // Get number of cars chosen 
    var carsCount = $(this).val(), 
     // Get a reference to the first input group so we can clone it 
     carInput = $('#car-inputs div:first'); 

    // Clone per number chosen 
    for (var i = 0; i < carsCount; i++) { 
     // Insert clone after original. 
     // IRL, you probably need to do some preprocessing on it first. 
     carInput.clone().insertAfter(carInput); 
    } 
}); 
+0

谢谢亚历克斯!我工作很棒。但是,如果我选择了4(错误),然后再选择3,它又增加了3个。我可以修改它,使其显示正确的金额,无论我更改了多少次? – 2011-04-19 09:49:16

+0

@Kenneth * easy *方法是除了第一个'#car-inputs select:gt(0)'和remove()'之外的所有选项。然而,为了保持文本在那里,你可以在循环中设置“i”等于元素的当前“长度”。 – alex 2011-04-19 10:11:50

+0

我不明白。你会在哪里使用这个?我想为此ID或NAME计数。我想我可以使用:GT以及在这里? – 2011-04-19 10:18:25

0

也许克隆可以帮助你:http://api.jquery.com/clone/

希望这有助于。

+0

我对Clone()很熟悉,但我不清楚如何将它与选择选项结合在一起... :-) – 2011-04-19 09:51:48