插入元素可防止触发单击事件
我有一个简单的表单验证器。当您在输入之外单击时,它会显示一条错误消息(必要时)。
然而,我注意到了一个副作用。当错误消息插入表单时,它会将提交按钮向下移动,从而防止触发提交事件。
看看下面的片段。这个过于简化的例子模拟了这个问题。尝试单击输入,然后单击按钮。您会注意到按钮的单击事件不会触发,因为它向下移动。
function insert() {
var button = document.querySelector('button');
document.body.insertBefore(document.createElement('div'), button);
}
div {
width: 100px;
height: 100px;
background-color: red;
}
<input onblur="insert()" />
<button onclick="alert()">Click</button>
我该如何解决这个问题?请记住,对于我的表单验证器,按钮的类型为提交,不会触发的事件是表单的提交事件,但显然可以在此处应用相同的概念。
I have a simple form validator. When you click away from the input, it displays an error message (when necessary).
However, I have noticed a side effect. When the error message is inserted into the form, it shifts the submit button downward, which prevents the submit event from firing.
Take a look at the snippet below. This overly simplified example emulates the problem. Try clicking on the input and then the button. You'll notice that the button's click event won't fire because it is shifted downwards.
function insert() {
var button = document.querySelector('button');
document.body.insertBefore(document.createElement('div'), button);
}
div {
width: 100px;
height: 100px;
background-color: red;
}
<input onblur="insert()" />
<button onclick="alert()">Click</button>
How can I resolve this problem? Keep in mind that for my form validator, the button is of type submit and the event that won't fire is the form's submit event, but the same concept can clearly be applied here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
alert()
未触发的原因是创建的div
元素是在click< 之前通过
blur
事件插入的/code> 事件发生。然后,当发生click
事件时,它不会向按钮注册,因为按钮在页面上移动了。在下面的示例中,我添加了一个delayInsert
函数来演示这一点。步骤:
Click
按钮alert()
将在插入div
之前触发。The reason the
alert()
isn't firing is because the createddiv
element is inserted with theblur
event before theclick
event occurs. Then when theclick
event occurs, it doesn't register with the button because the button is moved on the page. In the example below, I added adelayInsert
function to demonstrate this.Steps:
Click
buttonThe
alert()
will fire before thediv
is inserted.这对我有用。当我编辑 txt 框时,会附加 div。当我点击按钮时,它会发出警报。尝试使用js获取数据并向php发送xmlHTTPrequest?
It works for me. When I edit the txt box, the div is appended. When I click the button, it alerts. Try using js to get the data and send a xmlHTTPrequest to the php?