我想我會嘗試一個非jQuery的(也是非其他庫的解決方案,只是爲了......好,填入g幾分鐘):
function clickOrigin(e){
var target = e.target;
var tag = [];
tag.tagType = target.tagName.toLowerCase();
tag.tagClass = target.className.split(' ');
tag.id = target.id;
tag.parent = target.parentNode;
return tag;
}
var tagsToIdentify = ['img','a'];
document.body.onclick = function(e){
elem = clickOrigin(e);
for (i=0;i<tagsToIdentify.length;i++){
if (elem.tagType == tagsToIdentify[i]){
console.log('You\'ve clicked a monitored tag (' + elem.tagType + ', in this case).');
return false; // or do something else.
}
}
};
JS Fiddle demo。
修訂以上,以檢測嵌套在a
元素中img
元素(這是我認爲是你在想什麼已經重讀你的問題):
function clickOrigin(e){
var target = e.target;
var tag = [];
tag.tagType = target.tagName.toLowerCase();
tag.tagClass = target.className.split(' ');
tag.id = target.id;
tag.parent = target.parentNode.tagName.toLowerCase();
return tag;
}
var tagsToIdentify = ['img','a'];
document.body.onclick = function(e){
elem = clickOrigin(e);
for (i=0;i<tagsToIdentify.length;i++){
if (elem.tagType == tagsToIdentify[i] && elem.parent == 'a'){
console.log('You\'ve clicked a monitored tag (' + elem.tagType + ', in this case and one inside an "a" element, no less!).');
return false; // or do something else.
}
else if (elem.tagType == tagsToIdentify[i]){
console.log('You\'ve clicked a monitored tag (' + elem.tagType + ', in this case).');
return false; // or do something else.
}
}
};
JS Fiddle demo。
有一件事你可能將不得不應對最終的是,一些網站將有自己的處理程序鏈接點擊,這將是硬/不可能以確保您的處理程序首先調用。 – Pointy
@Pointy - 這是一個很好的觀點......甚至沒有考慮到這一點。我只需要向使用我的代碼的任何人指出典型的注意事項和免責聲明。 –