简体   繁体   English

如何防止JavaScript中的事件传播?

[英]How to prevent event propagation in javascript?

<script type="text/javascript">
function f1(a)
{
alert(a);
document.forms[0].elements[0].focus();
}
function f2(b)
{
alert(b);
document.forms[0].elements[1].focus();
}
</script>
<form name="myform">
<input type="text" name="box1" value="a" onblur=f1('a');  />
<input type="text" name="box2" value="b" onblur=f2('b');  />
</form>

The onblur event is fired every time and looping indefinitely.tried e.stopPropagation() still the same. 每次都会触发onb​​lur事件并无限期地循环。e.stopPropagation()仍然相同。 My purpose is to validate the textboxes when the user navigates to next form element.so this made me to call the function in onblur() 我的目的是在用户导航到下一个表单元素时验证文本框。因此这使我可以在onblur()中调用该函数

When an alert popup is opened, and you having to click on it causes the field that you were on the blur once again, which in turn makes another call to one of your functions (f1 or f2), and another alert popup appears. 当打开警报弹出窗口时,如果您必须单击它,则会再次使您处于模糊状态的字段,这又使您再次调用某个功能(f1或f2),并出现另一个警报弹出窗口。 Thus it is an endless cycle. 因此,这是一个无休止的循环。 stopPropagation will not help you here. stopPropagation对您无济于事。 Suggestion: don't use alert() . 建议:不要使用alert()

Now let's assume you didn't call alert() . 现在,假设您没有调用alert() You are still going to have a major usability problem here. 您仍然会在这里遇到一个主要的可用性问题。 After the user initially focuses on either of the text fields, they will never be able to enter the other text field, or any other input element, for that matter, because the initial field will continually require focus. 在用户最初将焦点放在任何一个文本字段上之后,就此而言,他们将永远无法输入另一个文本字段或任何其他输入元素,因为初始字段将持续需要焦点。

You could try and troubleshoot this or just leverage an industry proven package, example: jQuery. 您可以尝试对此进行故障排除,也可以仅使用经过行业验证的软件包,例如jQuery。 It helps you handle all kinds of event propagation and provides nice examples. 它可以帮助您处理各种事件传播,并提供了很好的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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