如何在使用jQuery克隆表单元素后调用AJAX函数?

我有一个可以使用SheepIt克隆的动态表单! 插件来克隆我的表单元素。 我的表单有一组动态下拉框,其中第二个下拉框根据第一个下拉框中的选择显示一组值。

我的问题是下拉框的动态function在克隆的下拉列表中不起作用,并且仅适用于页面上的第一个下拉列表。

任何想法为什么会这样?

我创造了一个小提琴,所以你可以看到SheepIt! 插件工作, http://jsfiddle.net/DeJch/1/ ,但添加/删除function不适用于小提琴。

克隆完成后我是否必须回忆起AJAX?

也许像$('#container_add').live('click', function() { */ */ });

HTML:

 
Select ...
... /select>

使用Javascript:

 $(document).ready(function(){ var sheepItForm = $('#clone').sheepIt({ separator: '', allowRemoveLast: true, allowRemoveCurrent: true, allowAdd: true, maxFormsCount: 3, minFormsCount: 1, iniFormsCount: 1 }); $(".item").change(function () { var group_id = $(this).val(); var self = $(this); // Added line var $children = $(this).parent().next().children('select.options') $.ajax({ type: "POST", url: "../../db/groups.php?id=" + group_id, dataType: "json", success: function(data){ $children.empty() $children.append('Select'); $.each(data, function(i, val){ $children.append('' + val.name + ''); }); $children.focus(); }, beforeSend: function(){ $children.empty(); $children.append('Loading...'); }, error: function(){ $children.attr('disabled', true); $children.empty(); $children.append('No Options'); } }) }); }) 

克隆完成后我是否必须回忆起AJAX?

 Maybe something like $('#container_add').live('click', function() { */ */ });? 

非常多,但不要使用.live()事件,因为它现在已被弃用。 请改用on()事件。 语法几乎相同

 $('#container_add').on('click', function() { */ */ }); 

on事件与live非常相似。 看看http://api.jquery.com/live/

即使你已经接受了你的回答,我还以为我会提到SheepIt! plugin提供以下回调:beforeClone,afterClone,beforeAdd,afterAdd。

如果在选项中指定afterAdd回调,则可以将其他function绑定到新创建的克隆表单。

 myCustomSheepitOptions = { separator:'', allowRemoveLast:false, allowRemoveCurrent:true, allowRemoveAll:true, allowAdd:true, allowAddN:false, maxFormsCount:10, minFormsCount:1, iniFormsCount:1, afterAdd:function (data) { initializeAutotab($('input.autotab', data)); initializeDatePicker(data); } }; 

好处是传递给afterAdd的数据只是您创建的新表单。

这种方法的缺点是,如果使用嵌套表单,则必须为嵌套选项指定相同的afterAdd。

无论如何,这是使用live / on的替代方案。

编辑:还要注意您要使用afterAdd而不是afterClone,因为afterClone似乎在内容实际添加到DOM之前。