【问题标题】:Why doesn't .change() work?为什么 .change() 不起作用?
【发布时间】:2016-02-26 00:21:21
【问题描述】:

我有html

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

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

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

我试过了

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

但是当{{offers}} 的值发生变化时,这永远不会记录任何内容

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

【问题讨论】:

  • 因为跨度没有更改事件,只有输入有。
  • h1-3 工作还是 p?
  • @chackerian 不,它不会
  • 您需要在渲染模板的同时进行更改操作。除此之外,跨度永远不会改变,每次“更新”时都会被完全替换
  • 也许你正在寻找更像stackoverflow.com/questions/32171413/…的东西

标签: javascript jquery events meteor event-handling


【解决方案1】:

您需要的是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,就会触发equal函数,然后开始运行你要运行的事件

【讨论】:

    【解决方案2】:

    另一种方法(我不知道它对你有多好用)是让输入“看起来”像一个 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;
    }
    

    【讨论】:

    • 仍然不会触发,因为 JS 改变了值并且 change 事件仍然不会触发。
    • 它仍然不会触发,因为每次更新都会通过模板替换整个 dang 输入...
    • @epascarello 我正在尝试一种创造性的方法(老实说不知道它是否可行),不过感谢您的意见。
    • 这是误导。 meteor 不能以 javascript 通常的正常方式工作
    猜你喜欢
    • 2013-01-25
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多