在JQuery中包装事件处理程序

我有OnBlur事件处理程序的一些输入

 

在JQuery Form准备好之后,我想把OnBlur事件hanlder转换成类似的东西

   

这意味着我想用一些额外的代码包装当前的事件处理程序。 在做了一些额外的工作之后,我想用setTimeOut()调用旧代码。
如果可以在客户端进行,如上所述?
我试过attr(),但它不起作用。
内容已更改,但在Blur上没有任何反应。
另外,我想,我不能在这种情况下使用Blur()/ Live()/ bind(),可以吗?

你所拥有的东西叫做DOM0处理程序 – 一个处理程序,它使用一种机制,它不是由任何DOM标准定义的,但是所有主流浏览器都支持这种机制。

在您的特定示例中,您可以使用jQuery附加您自己的blur处理程序,它附加一个现代或“DOM2”处理程序,它不会取代DOM0处理程序,因为您要做的就是添加一个setTimeout调用。 如果你想做任何其他事情 ,你必须做一些更复杂的事情,因为有些浏览器在调用DOM2处理程序之前调用DOM0处理程序,而其他浏览器在调用DOM0处理程序之前调用DOM2处理程序。 但同样,因为你所做的是触发异步(通过setTimeout ),这无关紧要,你不关心哪个首先被调用,因为你的超时代码无论如何都不会运行。

但是我们假设您想要做一些更有趣的事情:

您可以使用现代DOM2替换DOM0处理程序。 您只需从DOM元素的reflection属性中获取DOM0处理程序,替换自己的处理程序,然后从处理程序中调用DOM0函数。 您希望确保在它期望的上下文中调用DOM0处理程序,并使用它期望的参数。 像这样的东西(这个例子使用click而不是blur ,但在两种情况下都应该相同):

 var target, dom0handler; // Use jQuery to find the element target = $("#target"); // Did we find it? if (target[0]) { // Yes, get the DOM0 handler from the DOM element itself (not the jQuery object) dom0handler = target[0].onclick; // Get rid of it target[0].onclick = ""; // Hook up our own handler target.click(function(event) { display("Before calling DOM0 handler"); if (typeof dom0handler === "function") { if (dom0handler.call(this, event) === false) { event.preventDefault(); } } display("After calling DOM0 handler"); }); } 

实例

注意不对称性:我们读取了onclick属性并获得了一个函数,但我们为它分配了一个字符串。 为onclick分配空白字符串是清除处理程序的最广泛兼容方式(分配nullundefined在某些浏览器中不起作用)。 (好吧,好吧,另一种方式是target[0].onclick = function() { } ,但为什么在你不需要的时候创建一个函数。)


更新

从下面的评论中,您已经说过要在超时后调用DOM0处理程序。 只需将代码包装在闭包中调用它(并处理this问题),就可以轻松地做到这this

 var target, dom0handler, activeTimeout = 0; // Use 0 for "none" because 0 is not a valid return from `setTimeout` // Use jQuery to find the element target = $("#target"); // Did we find it? if (target[0]) { // Yes, get the DOM0 handler from the DOM element itself (not the jQuery object) dom0handler = target[0].onclick; // Get rid of it target[0].onclick = ""; // Hook up our own handler target.click(function(event) { var element = this; // Remember the element to a local, because `this` will have a different value inside the function called by `setTimeout` // If we have a function to call and we're not busy... if (activeTimeout === 0 && typeof dom0handler === "function") { // ...call it activeTimeout = setTimeout(function() { activeTimeout = 0; // Clear this since the timeout has occurred dom0handler.call(element, event); // Call the handler; we no longer care about its return value }, 100); } return false; }); } 

并在它发生之前取消它:

 if (activeTimeout !== 0) { clearTimeout(activeTimeout); activeTimeout = 0; } 

你能不能使用.blur()将blur事件绑定到元素?

http://api.jquery.com/blur/

例如

 $("#mytextbox").blur(function() { alert("lost focus"); }); 

供您参考:

  

你的脚本:

 function yourfunction(abc){ $("input").blur(function(){ var element =$(this); var I = element.attr("value"); if (I !== 'abc'){element.val('abc');} }); if(abc.length==0){ //if length is null do some stuff... } //do some more stuff here !! } 

注意: onkeyup="yourfunction(this.value);"