2014-01-22 27 views
0

小提琴 - http://jsbin.com/oloriTo/1/editJQuery的:動態刪除元素(隔離功能)

刪除元素是沒有問題的,但是當我點擊刪除按鈕錯誤(類.rf)我要不再刪除元素,除非單擊刪除true(class是.rt)按鈕。

當前,當我單擊刪除true元素時,它按預期方式執行。 (演示有點麻煩,但它得到了點)當我點擊刪除假按鈕,我仍然可以點擊.container div中的元素,並刪除它們,這不會發生。

任何幫助,非常感謝。

$(document).ready(function() { 
    var enabled = false; 
    $('.rt').click(function() { 
    enabled = true; 

    if (enabled === true) { 
     $('.container *').on('mousedown touchstart', function() { 
     $(this).remove(); 
     return false; 
     }); 
    } else { 
     enabled = false; 
    } 
    }); 

    $('.rf').click(function() { 
    enabled = false; 
    }); 
}); 
+0

條件沒有意義,'enabled'將始終爲真,因爲您在上面的行將其設置爲true。 – adeneo

+0

默認情況下,啓用的var設置爲false。當按鈕刪除true被點擊啓用時被轉換爲true,然後在刪除false按鈕被點擊時爲false。 –

+1

不管你設置的是什麼,你總是在條件之前將它重置爲true,所以就像'if(true === true)',它總是如此,你只是繼續打樁在事件處理程序上。 – adeneo

回答

3

你要綁定的設置啓用代碼中刪除代碼。打破它,讓它看看由.rf.rt設置的變量。

$(document).ready(function() { 
    var enabled = false; 
    $('.rt').click(function() { 
    enabled = true; 
    }); 

    $('.rf').click(function() { 
    enabled = false; 
    }); 
    $('.container').on('mousedown touchstart', '*',function() { 
     if (enabled)  
     $(this).remove(); 
     return false; 
    }); 
});