0

在我的 web 应用程序中,我需要创建许多具有不同内容(即文本和评级不同,按钮 ID 不同)的相同块(一些文本、评级、一些按钮)。为此,我正在使用 jQuery 模板。

同时,对于评分,我使用“Raty”jQuery 插件。它将评级显示为填充和空星的数量,并且在模板填充数据时应将值传递给它。

但是,在模板处理时,我找不到将插件应用到相应 div 的方法。

这是代码。

  1. 模板
    <script id="clientTemplate" type="text/html">
        <span class="firstline" id="firstline_${id}">${firstline}
        <div class="star" id="s_${id}" style="cursor: pointer; width: 100px;"></div>
        {{if unescape( alert($data.importance)  )}}{{/if}}
        </span>
    </script>
    
    //警报只是为了检查我们是否可以访问必要的数据
  2. 这就是我们需要应用于stardiv 的内容: //我需要将值替换为下面 的值
    $(".star").raty({
        half : true,
        score : 2.5,
        readOnly : false,
        click : function(score, evt) {
            if (readonly) {
                return false;
            }
            _id = $(this).attr("id");
            _id = id.replace("s", "");
            _id = _id.trim();
                $.ajax({
                    url : "importancereceive.html",
                    type : "POST",
                    data : {
                    id : _id,
                    importance : score
                },
                success : function(data) {
                    if (data != "1") {
                        alert("Failed to mark plan as completed");
                    }
                },
                error : function(jqXHR, textStatus, errorThrown) {
                    alert("error: " + textStatus);
                    alert("error: " + errorThronwn);
                }
            });
        }
    });
    
    scoreimportance
  3. 这是数据
    <script>
        var clientData = [ {
            id : 1,
            firstline : "My first line",
            importance : 2.0
        } ];
    </script>
    

如何在生成时将此插件应用于每个stardiv?我知道,知道项目的 id 我可以遍历整个 DOM 并将特定importance值设置为特定的stardiv,但这意味着多次遍历整个 DOM,这可能会给手机/平板电脑带来问题,尤其是. 如果列表变大。有没有办法在生成时将上述内容应用于 div?

4

2 回答 2

1

将重要性存储在 的自定义属性中不是一个想法div吗?

所以你的模板会变成这样:

<script id="clientTemplate" type="text/html">
    <span class="firstline" id="firstline_${id}">${firstline}
    <div class="star" id="s_${id}" style="cursor: pointer; width: 100px;" data-importance="${importance}"></div>
    {{if unescape( alert($data.importance)  )}}{{/if}}
    </span>
</script>

(我想是这样的,我不知道你的模板语言)

另请参阅是否可以将您自己的属性添加到 HTML 元素?有关创建自己的属性的更多信息。

然后你可以使用$(this).attr("data-importance").

编辑:然后你可以使用$(this).data("importance"). (见来源

于 2012-12-30T15:21:53.133 回答
1

与许多依赖于每个实例的特定数据的插件一样,您必须遍历元素才能将正确的数据应用于每个实例。

如前所述,data-使用模板将分数存储在属性中

$('.star').each(function(){
     var score=$(this).data('score')
     $(this).raty({
           half : true,
           score : score,
          /* other options*/
     });  
});

您的模板引擎应该允许您访问它在插入之前生成的 html。

您可以在它生成的 html 上调用插件,也可以在插入 DOM 之前遍历该 html。

一些模板引擎在如何处理这个问题上更灵活一些。这取决于使用的模板系统

于 2012-12-30T16:34:51.860 回答