[英]Can you refer to the element on which a handler called a function?
我通常從不使用這種編程風格,但以為我會嘗試一下,以便了解它的最新情況。
這是我的輸入標簽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');
}
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");
}
演示: http : //jsfiddle.net/mWLTw/
<input id="Read" type="checkbox" onclick="readClicked(this)" checked>
function readClicked(elem) {
console.log(elem);
console.log($(elem));
alert('Read Clicked!');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.