2013-05-30 23 views
1

我通常從來不會使用這種編程風格,但我認爲我會試一試,以便我知道它是怎麼回事。您可以引用處理程序調用函數的元素嗎?

這是我的輸入標記HTML: <input id="Read" type="checkbox" onclick="readClicked()" checked>

和我相關的功能:

function readClicked() { 
    console.log(this); 
    console.log($(this)); 
    alert('Read Clicked!'); 
} 

反正有指其中那個叫readClicked處理程序()從內部被稱爲元素功能? 喜歡的東西:

function readClicked() { 
    var caller = function.caller; 
    var type = $(caller).attr('type'); 
} 

回答

3

this作爲參數:

onclick="readClicked(this);" 

然後你的函數是:

function readClicked(el) { 
    var type = $(el).attr('type'); 
} 

雖然,因爲你使用jQuery,我建議結合事件與jQuery,而不是內聯。就像這樣:

$("#Read, #OtherElement").on("click", clickHandler); 

function clickHandler() { 
    var type = $(this).attr("type"); 
} 

DEMO:http://jsfiddle.net/mWLTw/

+3

咄,我也許應該嘗試,然後再發布。 – dezman

3
<input id="Read" type="checkbox" onclick="readClicked(this)" checked> 

function readClicked(elem) { 
    console.log(elem); 
    console.log($(elem)); 
    alert('Read Clicked!'); 
} 
相關問題