我是这样做的:
$(".classname").bind("keypress",function(){
alert("event happened");
})类似于上面的代码,只工作一次,我的意思是,当你第一次输入并点击enter时,它是工作的,但下一次,它根本不起作用。
$("#id").bind("keypress",function(){
alert("haiii");
}) 第二个代码一直在工作,但第一个代码只工作一次。
此外,如果第二个代码运行一次,第一个代码甚至不会运行一次。
解决方案是什么?我想我在这里遗漏了一些规则,你能告诉他们吗,这样我就可以搜索他们。谢谢
发布于 2012-05-22 01:28:26
事件绑定器应该始终可用;如果不是,这是因为您正在更改HTML结构(附加或删除节点)。在您的示例中,您将在运行时动态更改HTML,因此需要使用.on()
尝试使用此选项,而不是.bind()
$('#id').on({
keypress: function () { alert("hi"); }
});
$('.ClassName').on({
keypress: function () { alert("hi"); }
});
// IF YOU KNOW CLASSNAME ELEMENTS ARE INSIDE A FIXED ELEMENT:
$('#FixedID').on({
keypress: function () { alert("hi"); }
}, '.ClassName');关于您的编码风格,您应该将事件处理程序和处理事件的函数分开。例如,处理程序也会执行代码,而不是这样:
// one function that does everything!!
$(document).ready(function() {
// bind events
$('#SomeID').on({
click: function () {
// huge wall of code that handles events
},
mouseenter: function () {
// another huuuuuuuge wall of code here
}
)};
});你应该有这样的东西:
$(document).ready(function () {
BindHandlers();
DoSomethingElseWithPageInit();
});
function BindHandlers() {
// handlers do just the handling of events; easy to see and understand
$('#SomeID').on({
click: function (e) { ClickOnSomeID(e); },
mouseenter: function () { MouseEnterOnSomeID(); }
)};
}
// here are the functions that process the event
function ClickOnSomeID(e) { ... }
function MouseEnterOnSomeID() { ... }发布于 2016-01-23 21:06:38
正如frenchie所说,这是因为你的html结构已经改变了。.live()已经正确地处理了这一点,但现在.on()是后继者。但您不应该在元素上使用on(),而应该在文档上使用:
$(document).on("keypress", "#id", function(){
alert("event happened");
})https://stackoverflow.com/questions/10689686
复制相似问题