2013-05-10 78 views
0

我有一个与事件关联的函数,比如onfocus(),在某些情况下,我希望能够执行默认函数以及一个或多个附加函数。Javascript,jquery将函数追加到事件

所以我不想替换原来的函数,但我想追加另一个,这样两个函数都会触发。

<div id="mydiv" onfocus="alert('hello');"> 
if(something == somethingelse) $('#mydiv').onFocus += "alert('world');" 

因此,在这个例子中,有时仅仅你好会火,有时你好,然后世界将两者火。

我只是使用onfocus()和alert()作为例子,这些实际上是我定义的函数。

我该如何去做这件事?

回答

0

使用jQuery添加一个焦点事件处理程序

<script> 
    $('#mydiv').on('focus', function(){ 
     //do soemthing 
    }) 
</script> 
0

如果你用jQuery工作,不使用内联事件绑定,请使用以下代替:

$("#mydiv").on("focus", function() { 
    alert("hello"); 
}); 

// add one more action for the same event 
$("#mydiv").on("focus", function() { 
    alert("world"); 
}); 
0

你应该做

$('#myDiv').on('focus', function(){alert('world')}); 
0
$('#mydiv').focus(function(){ 
})//This is for the elements which load while the page is loading 

$('#mydiv').on('focus', function(){ 

}) //This is for the elements which will load dynamically after the page load completed. 
0

如果你不想使用jQuery试试这个,它的纯JavaScript等价的:

document.getElementById("mydiv").addEventListener("focus", function() { alert('world'); }); 

,如果你希望它是兼容IE8及以上,你应该尝试

var el = document.getElementById("mydiv"); 
if(el.addEventListener) 
    el.addEventListener("focus", function() { alert('world'); }); 
else 
    el.attachEvent("focus", function() { alert('world'); }); 
+1

需要之前,IE 9 – 2013-05-10 10:25:24

+1

的Internet Explorer版本的IE支持的测试,你必须使用'attachEvent'而比标准的'addEventListener'。 – 2013-05-10 10:26:46

0

,如果你使用jQuery,您要使用on()将事件处理程序绑定到的元素,而不是指定它们内嵌

$('#mydiv').on('focus', function() { 
    alert('hello'); 
}); 

$('#mydiv').on('focus', function() { 
    if (something === somethingelse) { 
     alert('world'); 
    } 
}); 

或组合成一个处理函数,在这种情况下,似乎是合理的

$('#mydiv').on('focus', function() { 
    alert('hello'); 

    if (something === somethingelse) { 
     alert('world'); 
    } 
}); 

当直列指定他们为你所做的一切,只有一个事件处理程序可以这样,如果你要绑定绑定到事件多个事件处理程序,您需要弯曲一个事件处理程序限制来处理此问题或使用其他方法,如DOM Level 2 events或其上的抽象(如jQuery的on()函数)。

当您绑定处理程序的元素存在于DOM中时,事件处理程序需要绑定。要做到这一点,你可以使用jQuery的ready()功能

// bind an event handler to the "ready" event on the document 
$(document).ready(function() { 
    // ..... here 
}); 

或简写

$(function() { 
    // ..... here 
});