2012-07-15 66 views
0

我正在尋找重寫下面的代碼,以便在第一次單擊時,而不是隻更改選擇器元素的圖像src,第二次單擊將圖像src更改爲images/spacer.gif,隨後的任何點擊都會在添加圖像src和將其替換爲間隔符之間循環。因爲這個函數使用單選按鈕和一個(事件),所以如果可能的話,我想遠離.toggle。下面的代碼塊僅適用於第一個功能。切換沒有使用.toggle

$('.item-button').click(function(event) { 
    var layerID = $(this).attr('data-layer'); 
    var itemID = $(this).attr('data-item'); 
    var selector = '#layer-' + layerID; 

      //an itemID of 0 means the item doesn't exist. 
    if (itemID == 0) { 
     $('#layer-' + layerID).attr('src', 'images/spacer.gif'); 
    } else { 
     var imageSrc = $(this).parent().find('img').attr('id'); 
     $(selector).attr('src', imageSrc); 
    } 
    }, 
    //a second nonfunctional function to change the src to the spacer in case the same radio button is clicked twice. 
    function(){ 
     $('#layer-' + layerID).attr('src', 'images/spacer.gif'); 
     }); 

回答

0

而不是看你的代碼,我給你一個片段,您可以自定義:

//set initial status 
$('element').data('status','not_clicked'); 

$('element').click(function(){ 
    if($(this).data('status') == 'clicked') { 
     $(this).data('status','not_clicked'); 

     //your code in case of second click 
    } else { 
     $(this).data('status','clicked'); 

     //your code in case of first click 
    } 
}); 

做些什麼:

  1. 設置初始狀態 - not_clicked
  2. 點擊的情況下:
    • 如果當前狀態爲clicked將其設置爲not_clicked(復位)並運行腳本
    • else - 將狀態更改爲clicked並運行腳本。