【问题标题】:Combine two collections of elements with mobify.js将两个元素集合与 mobify.js 结合
【发布时间】:2013-02-09 06:14:10
【问题描述】:

每个人。

我刚开始使用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>

我目前的解决方案是使用 ma​​p 功能,所以在 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。任何人都可以提出更好的解决方案吗?

【问题讨论】:

    标签: javascript mobile mobify mobify-js


    【解决方案1】:

    做这种事情的最好方法是将你的项目的相关属性(例如产品名称、图像 url 和链接 href)收集到 javascript 中的数据结构中,然后为你的新项目创建一个模板.tmpl 文件中的 html 结构。类似的东西

    '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;
    
    }
    

    然后通过遍历数组项并将它们插入到标记中的相关位置来对其进行模板化:

    <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>
    

    【讨论】:

      猜你喜欢
      • 2011-10-10
      • 1970-01-01
      • 2013-12-12
      • 1970-01-01
      • 2011-10-28
      • 2023-03-23
      • 1970-01-01
      • 2011-05-28
      • 1970-01-01
      相关资源
      最近更新 更多