如何在Meteor中切换文本中随机句子的颜色

时间:2016-06-17 01:06:57

标签: javascript jquery meteor

我的网站上有一个文字和几个标签,我想在每次点击标签时突出显示一个随机句子(同时标签变为"活动")。这是我的代码:

'click #mytag .selectize-control.multi .selectize-input [data-value]': function(){
   if($(event.target).attr('class') == "item"){
        $(event.target).removeClass().addClass('item active');
        var dataval = $(event.target).attr('data-value');
        //to "deactivate" other active tags
        $('.selectize-control.multi .selectize-input [data-value]').each(function(){ 
         if($(this).attr('class') == "item active" && $(this).attr('data-value') != dataval){
             $(this).removeClass().addClass('item');
          }
        });

       //generate a random random index and find the corresponding sentence to change the color
       Meteor.call("generateSentence",asin, function(error, result){
          Session.set("colorSentence", result);
       }); 
       var sid = Session.get("colorSentence");
       var id = 'span#sentence'+sid.toString();
       $(id).css("background","yellow"); 
    }
  }

每次点击一个标签,我都会得到一个背景颜色为黄色的随机句子。但是,我想在下次单击另一个标签时关闭颜色,以便每次只有一行背景颜色。谁能建议怎么做?

另外,为了只保留一个标签"活跃"每次,我遍历所有标签以检查其状态并关闭其他活动标签。它非常粗野,但至少可以起作用,因为我的标签太多了。但是因为这里有更多的句子,我不想在这里做同样的事情。我也很感激有关每次停用其他标签的更聪明方法的想法。谢谢

1 个答案:

答案 0 :(得分:1)

首先,为所有句子空间添加class="sentence"

现在,要停用您的背景,请执行

$('span.sentence').attr( style, '' );

其次,使用Session变量处理Meteor调用结果的方式是一种糟糕的模式。它使用了一个不必要的反应式观察者,并且比在回调中完成工作更难以遵循。总而言之,您的代码变为:

Meteor.call( "generateSentence", asin, function(error, result){
   $( 'span.sentence' ).attr( style, '' );
   $( 'span#sentence' + result ).css( "background", "yellow" ); 
}); 

使用jQuerys build处理多个元素选择,替换显式循环以停用标记,与清除句子样式的方式相同。