簡體   English   中英

同時觸發更改事件時未觸發單擊事件

[英]Click event not fired when change event fired simultaneously

我有一個我不知道的問題與事件的流星實現或一般的 Javascript 事件有關。

我有一個附加到“更改”事件的文本框。 在它旁邊,我有一個附加到“點擊”事件的按鈕。

當我在文本框中進行更改並單擊按鈕時,單擊事件不會觸發(只有更改事件會觸發)。 所以我必須點擊按鈕兩次才能觸發點擊事件。

在 Firefox 中,如果我將mousedown事件而不是 click 事件附加到按鈕,它就會起作用。 在 Chrome 中,這兩種方式都不起作用。

重現問題的最少代碼:

JAVASCRIPT:testevent.js

if (Meteor.isClient) {
  Session.set("something", "something");

  Template.hello.foo = function() {
    return Session.get("foo");
  };

  Template.hello.something = function() {
    return Session.get("something");
  }
  Template.hello.events({
    'click .buttonid' : function () {
      console.log("click !");
    },
    'change  .textid' : function (e,t) {
      console.log("change !");
      var bar = e.target.value;
      Session.set("foo",bar);
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}

HTML:testevent.html

<head>
  <title>testevent</title>
</head>

<body>
  {{> hello}}
</body>

<template name="hello">
  <input type="text" class="textid" value="{{foo}}"/>
  <input type="button" class="buttonid" value="{{something}}" />
</template>

當我用 id 替換 class 時,click 事件會觸發,但是當我有多個具有相同 id 的字段時,這些事件僅在一個字段上起作用。

問題與hello.foo

Template.hello.foo = function() {
  return Session.get("foo");
};

以及foo的值用於被動填充文本輸入的事實。 如果您刪除hello.foo函數,一切都會按預期工作。 當用戶單擊按鈕時,將觸發更改事件,該事件設置"foo"會話變量,從而導致模板重新呈現。 我認為渲染過程會清除剩余的事件隊列,因此單擊處理程序永遠不會觸發。

有幾種方法可以解決這個問題。 一種簡單(但粗略)的方法是在更改事件處理程序中延遲設置會話變量。 例如:

Meteor.setTimeout(function(){Session.set("foo", bar);}, 100);

顯然,您需要選擇適當的延遲,這可能取決於瀏覽器/數據。 或者,您可以將文本輸入放在自己的模板中。 例如:

<template name="hello">
  {{> helloText}}
  <input type="button" class="buttonid" value="{{something}}" />
</template>

<template name="helloText">
  <input type="text" class="textid" value="{{foo}}"/>
</template>

將事件正確綁定到這個新模板后,您會發現helloText將與hello分開呈現,因此您的事件將被保留。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM