运行后取消绑定事件处理程序:
$(function() {
$(".search_prompt").hide();
function show_search_prompt() {
$(".search_prompt").show();
$("#text").unbind("focusin", show_search_prompt);
}
function hide_search_prompt() {
$(".search_prompt").hide();
$("#text").unbind("focusout", show_search_prompt);
}
$("#text").bind("focusin", show_search_prompt);
$("#text").bind("focusout", hide_search_prompt);
});
工作示例
http://jsfiddle.net/bikeshedder/JqErw/
jQuery插件
如果您多次需要这个,您可以为此编写一个 JQuery 插件:
$.fn.bindRunOnce = function(eventType, eventHandler) {
this.bind(eventType, function cb() {
$(this).unbind(eventType, cb);
eventHandler.apply(this, arguments);
});
};
$(function() {
$(".search_prompt").hide();
$("#text").bindRunOnce("focusin", function(ev) {
$(".search_prompt").show();
});
$("#text").bindRunOnce("focusout", function() {
$(".search_prompt").hide();
});
});
现场演示
http://jsfiddle.net/bikeshedder/JqErw/1/
...或者您可以one
按照salexch
.
我怎么能错过这个?:-)