为什么没有.change()工作?

时间:2016-02-26 00:21:21

标签: javascript jquery events meteor event-handling

我有html

<span class="offersReceivedCount">3</span>

我希望在3值更改为其他值时运行代码。我使用了把手,所以真正的html看起来像

<span class="offersReceivedCount">{{offers}}</span> Offers Received</p>

我试过

$(".offersReceivedCount").change(function(){
console.log("change");
});

但是当{{offers}}的值发生变化

时,这永远不会记录任何内容

我是否需要不同的事件类型或尝试不同的方法?

2 个答案:

答案 0 :(得分:2)

您需要的是ReactiveVar,并在其上定义equality function

Template['your-template'].onCreated = function() {
   this['offerReact'] = new ReactiveVar(this['offers'], function(oldValue, newValue) {
       if (oldValue !== newValue) {
           // run the function you want to trigger when value change 
           return false;
       } else {
           // no change, do nothing, just return true;
           return true;
       }

   });
}

因此,每当您将新值设置为offerReact时,将触发相等的函数,然后开始运行您要运行的事件

答案 1 :(得分:1)

一种不同的方法(我不知道它对你的效果如何)将使输入“看起来”像一个span标签,请参阅小提琴:https://jsfiddle.net/f1a990f1/

然后您的代码将有效,更改功能不适用于span标记。

HTML

<input class="offersReceivedCount" type="text" value="333">
<script>
  $(".offersReceivedCount").change(function() {
    alert("change");
  });

</script>

CSS

input {
  border: none;
  outline: none;
  background-color: transparent;
  font-family: inherit;
  font-size: inherit;
}
相关问题