2011-10-18 44 views
0

我正在創建一個使用jQuery插件翻轉的馬賽克瓷磚牆! (http://lab.smashup.it/flip/)在每個磁貼上展示更多內容。我不是一個JavaScript或jQuery大師,但我已經在IE7 +,FF,Chrome和Safari中完美工作(拍背)。但是,我知道可以用更少的JS完成,並且我想了解如何。如何從jQuery Flip動畫的每個實現中分離內容?

我用下面的標記構成每一瓦:

<li id="tileID" class="tile">Default visible content 
    <div id="tileID_flipped" class="hiddenContent"> 
    Content made visible when tile flips. 
    </div> 
</li> 

文本「默認可見內容」是默認的(廢話)瓦片內顯示的內容。 <div id="tileID_flipped" class="hiddenContent">內的內容是當瓷磚翻轉時顯示的內容。

我使用內$(document).ready(function() {下面的JavaScript,使每個拼貼翻轉的工作:

$('#tileID').delegate('a', 'click', function(e){ e.stopImmediatePropagation(); }) 
.toggle(function(){ 
     $(this).flip({ 
     direction:'rl', 
     color: "#b91317", 
     content: $("#tileID_flipped"), 
     speed: 200 
     }) 
    }, 
    function() { 
     $(this).revertFlip() 
    } 
); 

通知你,我用e.stopImmediatePropagation()的解決方案,以防止當用戶點擊一個被觸發翻轉事件在瓦片內的鏈接。在這個網站上找到解決方案。

問題是,我爲每個創建的圖塊重複此腳本。我覺得這是浪費,因爲唯一的特性是content: $(selector)

我能夠翻轉事件適用於與類「平鋪」的每一個元素使用下面的代碼:

$('.tile').delegate('a', 'click', function(e){ e.stopImmediatePropagation(); }) 
.toggle(function(){ 
    $(this).flip({ 
     direction:'rl', 
     color: "#b91317", 
     speed: 200 
    }) 
}, 
function() { 
    $(this).revertFlip() 
} 
); 

現在,我已經做到了這一點,我怎麼「注入」的瓦片具體內容到每個瓦片?

P.S.我使用jQuery(1.6.4),jQuery UI(1.7.2)和jQuery翻轉。

回答

0

將選擇器存儲在數組中並循環。如果別的東西改變了,除了選擇器,我也爲它創建了一個對象。

(function(){ 
var selectors = "#tileID #someAnotherID #thirdID".split(" "); 

var selectorData = { 

    "#tileID": { 

    //Data concerning #tileID 
    }, 

    "#someAnotherID": { 

    }, 

    "#thirdID": { 


    } 
}; 

$.each(selectors, 
    function(index, selector){ 
    var data = selectorData[selector]; 

     $(selector).delegate('a', 'click', function(e){ e.stopImmediatePropagation(); }) 
     .toggle(function(){ 
      $(this).flip({ 
      direction:'rl', 
      color: "#b91317", // could be data.color and so on 
      content: $(selector+"_flipped"), 
      speed: 200 
      }) 
      }, 
      function() { 
      $(this).revertFlip() 
      } 
     ); 
    } 
); 

})() 

我使用$ .each進行迭代,因爲無論如何每個迭代都需要閉包。

+0

就像一個魅力,謝謝!我會贊成,但我沒有足夠的聲譽。 –

0

以與其他任何東西相同的方式抓取內容,從函數的上下文中遍歷。

 ... 
     content: $(this).find('.hiddenContent'), 
     ...