jQuery:解除绑定后如何返回鼠标事件?
我需要在鼠标进入 TD 元素时显示文本输入,并在鼠标离开时隐藏。因此,当我们单击此输入(焦点)时,它会解除鼠标事件的绑定......我应该编写什么来将标准操作绑定到 mouseenter 和 mouseenter 上? mouseleave,当我们在输入中按回车键?
$(".translation").mouseenter(function(){
$(this).html('<input type="text" class="tr_input" placeholder="Перевести...">');
$(".tr_input").focus(function(){
$(".translation").unbind("mouseenter");
$(".translation").unbind("mouseleave");
});
});
$(".translation").mouseleave(function(){
$(this).html("");
});
I'm need to show text-input, when mouse enteres the TD element and hide, when it leaves. So, when we click into this input (focus), it unbinds the mouse-events.......what i should write to bind the standart actions to the mouseenter & mouseleave, when we press Enter in the input?
$(".translation").mouseenter(function(){
$(this).html('<input type="text" class="tr_input" placeholder="Перевести...">');
$(".tr_input").focus(function(){
$(".translation").unbind("mouseenter");
$(".translation").unbind("mouseleave");
});
});
$(".translation").mouseleave(function(){
$(this).html("");
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您可以使用
display:none
创建一次(也许直接在 HTML 中),而不是每次都重新创建输入。当鼠标进入您的td
时,隐藏其中的所有内容并显示您的输入。然后,当鼠标离开您的输入时,您会再次隐藏它并显示之前的内容(如果有的话)。这样您就不需要动态绑定和取消绑定元素。
更新:我想我误解了你的问题。也许其他人知道如何正确绑定和取消绑定事件处理程序(我不知道),但也许我可以帮助您解决您的问题。如果我理解正确的话,您正在尝试执行类似于编辑表格内容的操作,对吧? (就像电子表格)
因此,我上面的建议仍然适用,但是您希望阻止这些处理程序在用户单击输入后运行。由于一次只有一个元素具有焦点,因此您可以创建一个
lock
变量,并在用户编辑它时将其设置为 true:并在运行每个处理程序之前对其进行测试:
当用户按 Enter 键(或者输入失去焦点),您可以再次设置
lock = false
并运行与mouseleave
相同的代码(因为鼠标可能已经离开了用户正在编辑)。完整的工作示例位于 jsFiddle。希望有帮助!
Instead of recreating the input every time, I think you could create it once (maybe directly in your HTML) but with
display:none
. When the mouse enters yourtd
, hide whatever's there and show your input.Then, when the mouse leaves your input you hide it again and show what was there before (if anything). This way you won't need to bind and unbind elements on the fly.
Update: I think I misunderstood your question. Maybe someone else knows how to properly bind and unbind event handlers (I don't), but maybe I can help you solve your problem. If I understood correctly, you're trying to do something similar to editing the contents of a table, right? (like a spreadsheet)
So, my suggestion above still applies, however you want to prevent those handlers from running after the user clicked on the input. Since only one element will have focus at a time, you could create a
lock
variable and set it to true while the user is editing it:And test for it before running each of your handlers:
When the user presses enter (or the input loses focus), you can set
lock = false
again and run the same code you would for themouseleave
(because the mouse might already have left while the user were editing).Full working example at jsFiddle. Hope it helps!