onchange event not fire when the change come from another function

前端 未结 5 877
耶瑟儿~
耶瑟儿~ 2020-11-30 12:33

I have a input text that get his value from a Javascript function (a timer with countdown).

I want to raise an event when the input text is 0 ,so i am using the chan

5条回答
  •  -上瘾入骨i
    2020-11-30 13:00

    Simply redefine the "value" property of the node, using getAttribute("value") and setAttribute("value", newValue), in the getters and setters, as well as dispatch the "change" event at the end of the setter. For example:

    myNode.onchange = e => console.log("Changed!", e.target.value);
    
    Object.defineProperty(myNode, "value", {
      get: () => myNode.getAttribute("value"),
      set(newValue) {
        myNode.setAttribute("value", newValue);
        myNode.dispatchEvent(new Event("change")); //or define the event earlier, not sure how much of a performance difference it makes though
      }
    })
    
    var i = 0;
    setTimeout(function changeIt() {
        if(i++ < 10) {
            myNode.value = i;
            setTimeout(changeIt, 1000);
        }
    }, 1)

提交回复
热议问题