2013-02-23 83 views
0

每個人。將mobify.js的兩個元素組合起來

我剛開始使用mobifyjs工具包,我遇到了將兩個元素集合在一起的問題。 在一個頁面上,我正嘗試移動,有兩組鏈接:文本和圖像。該HTML如下所示:

<!-- links with text --> 
<div id="products"> 
    <a href="Product1">Product 1</a> 
    <a href="Product2">Product 2</a> 
</div> 
... 
<!-- somewhere else on the page --> 
<div id="productImages"> 
    <a href="Product1"><img src="Product1.png /></a> 
    <a href="Product2"><img src="Product2.png /></a> 
</div> 

它需要轉成以下幾點:

<div class="items"> 
    <div class="item"> 
     <div class="img"> 
      <a href="Product1"><img src="Product1.png /></a> 
     </div> 
     <div class="title"> 
      <a href="Product1">Product 1</a> 
     </div>  
    </div> 
    <div class="item"> 
     <div class="img"> 
      <a href="Product2"><img src="Product2.png /></a> 
     </div> 
     <div class="title"> 
      <a href="Product2">Product 2</a> 
     </div>  
    </div> 
</div> 

我目前的解決方案是使用地圖功能,所以在mobify.konf我有這樣的事情以下:

'content': function(context) { 
    return context.choose(
     {{ 
      'templateName': 'products', 
      'products': function(){ 
       return $('#productImages a').map(function() { 
        var href = $(this).attr('href') || ''; 

        var div = $('<div class="item"><div class="img"></div><div class="title"></div></div>'); 
        div.find('.img').append($(this).clone()); 
        div.find('.title').append($('#products a[href="' + href + '"]').clone()); 

        return div; 
       }); 
      } 
     }) 
} 

而且模板是:

<div class="items"> 
    {#content.products} 
     {.} 
    {/content.products} 
</div> 

這段代碼確實有效,但由於我必須將一段標記代碼從tmpl文件移動到mobify.konf中,所以這種方法本身非常醜陋。任何人都可以提出一個更好的解

回答

1

做這種事情的最好方法是收集您的項目的相關屬性(例如產品名稱,圖像url和鏈接href)到javascript中的數據結構中,然後爲您的項目創建一個模板.tmpl文件中的新html結構。

<div class="items"> 
{#content.products} 
    <div class="item"> 
     <div class="img"><img src="{.imgSrc}" /></div> 
     <div class="title"><a href="{.href}">{.name}</a></div> 
    </div> 
{content.products} 
</div> 
:像

'products': function() { 
    var products = [], 
     $productLinks = $('#products a'), 
     $productImages = $('#productImages img') 
     len = $productNames.legnth; 
    for(var i = 0; i<len; i++) { 
     var $link = $productLinks.eq(i); 
     var $img = $productImages.eq(i); 
     products.push({name: $link.text(), href: $link.attr('href'), imgSrc: $img.attr('src')}); 
    } 
    return products; 

} 

,然後東西通過循環陣列項目,將它們插入到該標記相關的地方它模板