2010-09-29 33 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(); 
});