2013-07-29 55 views
1

我得到了jQuery代碼的問題。下面是代碼:jQuery點擊事件不會獨立工作

code sample

問題部分符合:

$(document).unbind('click').on('click', '#a_del', function() { 
    $('.a_frm > .frmlabel:last').remove(); 
    a_counter--; 
    $('#a_field_count').attr('value', a_counter); 
    }); 

$(document).unbind('click').on('click', '#b_del', function() { 
    $('.b_frm > .frmlabel:last').remove(); 
    b_counter--; 
    $('#b_field_count').attr('value', b_counter); 
    }); 

問題是,刪除按鈕兩種形式不起作用。如果我只添加一個刪除按鈕代碼,那麼它會正確刪除表單域。但是,當我添加第二個表單刪除按鈕的代碼,然後只能使用最新的表單刪除按鈕和第一個表單按鈕不再工作了..我不明白是什麼問題。 謝謝!

+0

當你用'on'綁定一個事件時,你應該使用'off'而不是'unbind'。 (http://api.jquery.com/on/) – putvande

回答

2

使用關和命名空間:

DEMO

$(document).off('click.a').on('click.a', '#a_del', function() { 
    $('.a_frm > .frmlabel:last').remove(); 
    a_counter--; 
    $('#a_field_count').attr('value', a_counter); 
    }); 

$(document).off('click.b').on('click.b', '#b_del', function() { 
    $('.b_frm > .frmlabel:last').remove(); 
    b_counter--; 
    $('#b_field_count').attr('value', b_counter); 
    }); 

但是當你使用的授權,我不知道你爲什麼要取消綁定呢?!

+0

非常感謝它現在的作品。 :) – Sangsom