简体   繁体   中英

Why doesn't .change() work?

I have the html

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

and I want to run code when the 3 value changes to something else. I'm using handlebars so the real html looks like

<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

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.

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

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/

Then your code will work sense the change function does not work with the span tag.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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