0

对不起这个可怕的标题,但基本上我正在做的是,我有一个模板,当按下加号按钮时会生成一个主干视图。这是一个非常简单的表单,有一些文本输入和选择下拉菜单。我想通过突出显示重复的区域来验证表单。目前在我的下划线模板中,我有

<div id="#index1-<%=dataId%>">

所以我的具有 dataId 属性的模型使 id 是唯一的。然后我可以按属性选择以红色突出显示该 div。当我在搜索如何选择以某些东西开头的 id 时,我遇到了这篇文章:jquery 如何选择所有以“text-”开头的类元素?

作者讨论了如何使用类来代替。当我验证时,我正在做的是添加一类样式error以突出显示红色和其他东西。因此,遍历页面上使用加号按钮添加的所有子视图如下所示:

       var lastIndex1;
       _.each(this.childViews, function (childView) {
            var dataId = childView.model.get('dataId');

            var index1 = childView.$('#index1-' + dataId).val();
            if (lastIndex1 == index1) {
                $('#index1-' + dataId).addClass('error');
            } else {
                lastIndex1 = index1;
                $('#index1-' + dataId).removeClass('error');
            }
        });

所以基本上,我最终会遍历我的视图,如果当前视图有问题,我会添加我的error类。我想知道这个实现是否可以通过在 html 中使用某种类来改进,所以我根本不必使用 dataId。

原来我第一次写代码的时候,如果最后不加dataId,那么只会高亮其中一个不正确的id(因为多个item的id相同)。类可以适用于这种情况吗?提前致谢!

4

1 回答 1

0

if you are assigning a unique id to each element then it should work just the same as using a class name. Your issue may be with your first line in the childView function,. your dataId var may be getting the same value each time, and not the current item you are iterating over. Im not familiar with undescore, but you might try something like var dataId = this.model.get('dataId');

于 2013-04-04T03:29:45.293 回答