简体   繁体   English

为什么.change()不起作用?

[英]Why doesn't .change() work?

I have the html 我有HTML

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

and I want to run code when the 3 value changes to something else. 我想在3值更改为其他值时运行代码。 I'm using handlebars so the real html looks like 我正在使用把手,所以真正的html看起来像

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

I tried 我试过了

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

But this never logs anything when the value of {{offers}} changes 但这不会在{{offers}}的值更改时记录任何内容

Do I need a different event type or maybe try different approach? 我需要其他事件类型还是尝试其他方法?

What you need is a ReactiveVar and define an equality function on that. 您需要一个ReactiveVar并在其上定义一个相等函数

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

   });
}

So, whenever you set the new value to the offerReact , the equal function will be triggered and then start to run the event you want to run 因此,无论何时将新值设置为offerReact ,都会触发equal函数,然后开始运行要运行的事件

A different approach (I don't know how well it would work for you) would be to make an input "look" like a span tag, see fiddle: https://jsfiddle.net/f1a990f1/ 另一种方法(我不知道它对您的效果如何)是使输入看起来像span标记,请参见小提琴: https : //jsfiddle.net/f1a990f1/

Then your code will work sense the change function does not work with the span tag. 然后您的代码将正常工作,感觉到更改功能不适用于span标记。

HTML HTML

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

</script>

CSS CSS

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM