为什么在我的示例中,提交按钮仅在按两次时才起作用?
请看这个小提琴:
当提交按钮时按下一次,它会无缘无故地删除文本编辑,但不会执行任何操作,但第二次按下时它会起作用,并转到页面。
请帮我解释一下这段代码是如何做到这一点的。
谢谢
HTML:
<b class = "edit" id = "fooo"> FOO </b>
JS:
$('b.edit').click(function() {
$(this).hide().after('<form action = "foo.php" method = post><input hidden name = "field" type = "text" value = "' + this.id + '"/><input type="text" name = "period" class="editP" value="' + $(this).html() + '" /><input type = "submit" value = "Submit!!" /></form>');
$('.editP').focus();
});
$('.editP').live('blur', function() {
$(this).hide().prev('b.edit').html($(this).val()).show();
});
Please look at this fiddle:
When the submit button is pressed once, It removes the text edit for no apparent reason, but doesn't do anything, but the second time, it does work when pressed, and goes to the page.
Please help me with what makes this code do that.
Thanks
HTML:
<b class = "edit" id = "fooo"> FOO </b>
JS:
$('b.edit').click(function() {
$(this).hide().after('<form action = "foo.php" method = post><input hidden name = "field" type = "text" value = "' + this.id + '"/><input type="text" name = "period" class="editP" value="' + $(this).html() + '" /><input type = "submit" value = "Submit!!" /></form>');
$('.editP').focus();
});
$('.editP').live('blur', function() {
$(this).hide().prev('b.edit').html($(this).val()).show();
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是,在您设法单击按钮之前,编辑框会失去焦点,从而更改位置,以便您不会点击按钮。
The problem is that the edit box loses focus before you manage to click the button thus changing the position so that you won't hit the button.
这就是您的代码所说的:
因此,当您第一次单击“提交”时,它实际上会触发模糊事件并隐藏输入。
此外,您的旧文本不会重新显示,因为您使用
.prev
来获取它。这会选择前一个相邻的同级元素,但由于输入元素位于表单中,因此另一个元素不是同级元素。这个小提琴应该让问题变得更加明显。请注意初始警报如何不检索文本 FOO。另请尝试单击“提交”按钮。
http://jsfiddle.net/uNbYu/8/
This is what your code says:
So when you click submit the first time it is actually firing the blur event and hiding the input.
Also, your old text is not being reshown because you use
.prev
to get it. This select previous adjacent sibling, but because the input element is in a form, the other element is not a sibling.This Fiddle should make what is wrong more obvious. Note how the initial alert does not retrieve the text FOO. Also try and click submit button.
http://jsfiddle.net/uNbYu/8/
1) 当您单击文本时,您的代码将创建表单并将焦点放在
.editP
上。2)代码的其余部分表示在失去焦点(模糊)时隐藏
.editP
。3) 因此,尝试单击按钮的行为会导致
editP
上触发模糊事件。这会隐藏.editP
,从而将其移到按钮上,从而防止其被单击。它发生得非常快......在您真正成功单击按钮之前。1) When you click the text, your code creates the form and put the focus on
.editP
.2) The rest of your code says to hide
.editP
when it loses focus (blur).3) So the act of trying to click the button causes the blur event to trigger on
editP
. This hides.editP
thus shifting over the button which prevents it from being clicked. It happens very fast... before you can actually successfully click the button.