2010-09-29 34 views
1

我建立在一个动态的形式,用户可以不断添加条目,直到他们满意,要做到这一点,我用这个JavaScript,以便在某些HTML拉,

$('#add_another').click(function(e){ 
    $.get('/admin/add_grade_course', function(data) { 
     $('#added_by_ajax').append(data); 
    }); 
    e.preventDefault(); 
}); 

的HTML被返回是一个如下所示,

<fieldset> 
    <select name="course_type"> 
     <option value="Classroom based learning">Classroom Based Learning</option> 
     <option value="Apprenticeship based learning">Aprenticeship Based Learning</option> 
     <option value="On the Job Learning">On The Job Learning</option> 
    </select> 
    <label for="course_names">Course Name</label> 
    <input type="text" name="course_names" value="<?php set_value('course_names');?>"/> 
    <?php echo form_error('course_names'); ?> 

    <label for="course_links">Course Links</label> 
    <input type="text" name="course_links" value="<?php set_value('course_links');?>"/> 
    <?php echo form_error('course_links'); ?> 

    <label for="grade_desc">Description of Grades Needed</label> 
    <textarea name="grade_desc"><?php set_value('grade_desc')?></textarea> 

    <a href="#" class="remove_fields">Delete</a> 


</fieldset> 

我的问题是,当你可以看到有什么独特之处是动态创建的报名表,如果用户又增加了一个新的输入字段,然后决定他们不需要它,我将如何去除最后添加的表单元素?,我假设我需要以某种方式得到th e点击的.remove_fields链接的父级字段集?我怎么做,没有选择页面上的所有字段集?

回答

0

会结合使用活()函数 click事件并删除以下选择条目。 live函数非常方便,因为它意味着任何匹配选择器的动态添加标记都会在添加时绑定函数。这意味着每次用户单击add_another链接时,新返回的fieldset都具有绑定到其remove_fields链接的click事件的函数。

$(function(){ //shorthand for $(document).ready(function(){ 
    $('.remove_fields').live('click', function() { 
     //$(this).parent() returns the current fieldset, remove() removes it. 
     $(this).parent().remove(); 
    }); 
}); 
1

使用closest - 方法:

// Add a delegated click-handler for clicks on remove-links 
$('body').delegate('a.remove_fields', 'click', 
    // In the event handler, remove the fieldset this link belongs to 
    function (e) { 
     // this refers to the link that was clicked. 
     // closest traverse the DOM upwards until it finds an ancestor 
     // matching the selector. (i.e. a fieldset). 
     // After we find this ancestor, we remove it from the DOM. 
     $(this).closest('fieldset').remove(); 
    } 
); 
0

像这样的东西可能会奏效:

var form_counter = 0; 
$('#add_another').click(function(e){ 
    $.get('/admin/add_grade_course', function(data) { 
     $(data).attr('id', 'form_' + form_counter); 
     var form_count_ref = form_counter; 
     $('a:last', data).onclick(function(){ 
       $('form_' + form_count_ref).remove(); 
     }); 
     form_counter++; 
     $('#added_by_ajax').append(data); 
    }); 
    e.preventDefault(); 
});