这是JSFiddle exapmle:https://jsfiddle.net/1a6j4es1/1/
$('table').on('click', 'td', function() {
$(this).css('background', 'green');
});
如何在纯JavaScript中重写此代码?
回调函数甚至应该适用于td
元素中的新table
元素。
更新:我发现了一个非常简短的解决方案:https://jsfiddle.net/1a6j4es1/28/
function delegateSelector(selector, event, childSelector, handler) {
var is = function(el, selector) {
return (el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector).call(el, selector);
};
var elements = document.querySelectorAll(selector);
[].forEach.call(elements, function(el, i){
el.addEventListener(event, function(e) {
if (is(e.target, childSelector)) {
handler(e);
}
});
});
}
delegateSelector('table', "click", 'td', function(e) {
e.target.style.backgroundColor = 'green';
});
答案 0 :(得分:1)
<table id="clickable" onclick="changecolor(this)" border=1>
<tr><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td></tr>
</table>
<script>
function changecolor(table)
{
document.getElementById("clickable").addEventListener("click",tableClicked);
function tableClicked(e) {
e.target.style.backgroundColor = 'green';
}
}
</script>
这对我有用..
答案 1 :(得分:0)
为要单击的元素添加ID,并使用以下代码:
document.getElementById("tableId").addEventListener("click", function(e){
e.target.style.background = 'green';
});