简体   繁体   English

在更改事件中隐藏元素时如何阻止事件触发

[英]How to stop event from firing when hiding element in a change event

I've found a bug when I'm using a keyboard to select from a select drop down, the form containing the drop down is submitted, this only happens on IE.当我使用键盘从下拉列表中进行选择时,我发现了一个错误,提交了包含下拉列表的表单,这只发生在 IE 上。 The drop down is in a div and has a JS handler for the change event.下拉菜单在一个 div 中,并且有一个用于更改事件的 JS 处理程序。

In the handler the div containing the drop down is hidden, this causes a submit event to be triggered on whatever is currently focused on.在处理程序中,包含下拉列表的 div 被隐藏,这会导致在当前关注的任何内容上触发提交事件。

The problem can be solved by hiding the div from outside the context of the change event (using a setTimeout) but this doesn't explain why the issue is occurring.该问题可以通过在更改事件的上下文之外隐藏 div(使用 setTimeout)来解决,但这并不能解释为什么会出现问题。

Simplified example (the issue persists if jQuery is not used):简化示例(如果不使用 jQuery,问题仍然存在):

<form>
  <div id="container">
    <select id="select"></select>
  </div>
</form>

$("#select").on('change', function (e) {
  e.preventDefault();
  $("#container").hide(); <-- this causes the form to be submitted
})

Hiding the div shouldn't cause the form to be submitted, only IE and mobile browsers are showing this issue.隐藏 div 不应导致提交表单,只有 IE 和移动浏览器会显示此问题。

Edit: This is on IE 11 and Edge, I can get the same issue on 10 and 9 using the IE 11 emulator, I haven't tried lower versions.编辑:这是在 IE 11 和 Edge 上,我可以使用 IE 11 模拟器在 10 和 9 上遇到同样的问题,我没有尝试过低版本。

More code:更多代码:

<form>
    <div class="selectAddress u-hidden m-form-row m-form-row--full-width" style="display: block;">
        <label class="a-label" for="Contact_PolicyHolderAddress_FullAddress">Please select your address</label>
        <div class="m-form-row__content">
            <span class="a-dropdown">
                <select aria-required="true" autocomplete="off" class="a-dropdown__select addressList" id="Contact_PolicyHolderAddress_FullAddress"
                    name="Contact.PolicyHolderAddress.FullAddress">
                    <option aria-label="Please select" value="">Please select....</option>
                    <option>Option 1</option>
                    <option value="Address not found" class="notFound">Address not found</option>
                </select>
                <input class="addressList" id="Contact_PolicyHolderAddress_FullAddress" name="Contact.PolicyHolderAddress.FullAddress"
                    type="hidden" value="">
                <span class="a-dropdown__ui"></span>
            </span>
        </div>
    </div>
</form>

try to stop the event propagation :尝试停止事件传播:

$("#select").on('change', function (e) {
  e.preventDefault();
  e.stopPropagation();
})

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

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