防止 onchange 事件进入无限循环

发布于 2024-12-26 10:08:54 字数 501 浏览 4 评论 0原文

我有两个文本字段,一个代表百分比,第二个代表相应的金额。现在我想要的是,当百分比改变时,金额应该改变,当金额改变时,百分比也应该相应改变。我正在使用 JavaScript。

在这种情况下,如果其中任何一个发生变化,就会开始无限循环。

我想要的是,当金额发生变化时,它应该相应地改变百分比,然后循环应该停止。当百分比改变时,它应该相应地改变数量,然后循环应该停止。有什么办法吗?也许类似 stopPropagation

虚拟 JS 代码:

这里 value 是一个文本框,percentage 是另一个文本框

function valueChng(){
    percentage.value = "" + someInteger;
}
function percentageChng(){
    value.value = "" + someInteger;
}

谢谢!

I have two text fields, one represents a percentage and the second represents a corresponding amount. Now what I want is, when the percentage changes the amount should change and when the amount changes the percentage should change accordingly. I am using javascript.

In this case, if any of them changes an infinite loop will start.

What I would like is that when the amount changes, it should change the percentage accordingly and then the loop should stop. And when the percentage changes, it should change the amount accordingly and then the loop should stop. Is there any way for this? Maybe something like stopPropagation ?

Dummy JS Code:

Here value is one text box and percentage is another text box

function valueChng(){
    percentage.value = "" + someInteger;
}
function percentageChng(){
    value.value = "" + someInteger;
}

Thanks!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤云独去闲 2025-01-02 10:08:54

我在这里仍然没有看到问题,因为以编程方式更改内容时不会执行更改处理程序。我刚刚实现了一个简单的小提琴来展示它是如何工作的,而不会陷入无限循环(为简单起见,使用 jquery):
http://jsfiddle.net/aWuks/

I still don't see a problem here, as a change handler is not executed when the content is changed programmatically. I just implemented a simple fiddle to show how it is working without running into in infinite loop (using jquery for simplicity):
http://jsfiddle.net/aWuks/

半步萧音过轻尘 2025-01-02 10:08:54

从我的头脑中:

var changedFlag = false;

function valueChng(){
    if(changedFlag == true) {
      changedFlag = false;
      return;
    }

    percentage.value = "" + someInteger;
    changedFlag = true;
}
function percentageChng(){
    if(changedFlag == true) {
      changedFlag = false;
      return;
    }

    value.value = "" + someInteger;
    changedFlag = true;
}

这样两个“onchange”事件中的第二个事件将始终被忽略。

From the top of my head:

var changedFlag = false;

function valueChng(){
    if(changedFlag == true) {
      changedFlag = false;
      return;
    }

    percentage.value = "" + someInteger;
    changedFlag = true;
}
function percentageChng(){
    if(changedFlag == true) {
      changedFlag = false;
      return;
    }

    value.value = "" + someInteger;
    changedFlag = true;
}

This way second of two 'onchange' events will be always ignored.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文