2013-05-10 114 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 
});