[英]e.target() not working for table element
The event.target
function works well for div and not for table element. event.target
函数适用于div而不适用于table元素。
html code: HTML代码:
<div class="one body" >
sd
</div>
<div class="two body">
sddsd
</div>
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="three body">jjj</table>
js: JS:
$(".body").click(function(e){
alert("xxxxxxxxx"+e.target.className);
});
DEMO: http://jsfiddle.net/kavinhuh/z4rkW/31/ 演示: http : //jsfiddle.net/kavinhuh/z4rkW/31/
Cause the actual e.target is a TD, not a table 因为实际e.target是TD,而不是表
Though you have an incorrect Table HTML Element structure. 虽然您有不正确的表HTML元素结构。 Tables are expected to have
tr
and td
elements. 表应具有
tr
和td
元素。
alert("Class: "+ event.target.className );
// is the Element that first fired the event ( TD
) //是首先触发事件的元素(
TD
)
alert("Class: "+ this.className );
// is the element that was delegated to the event, in this case .body
//是委托给事件的元素,在本例中为
.body
This is because your HTML is illegal. 这是因为您的HTML是非法的。 If you have illegal HTML, you should not expect your code to work properly.
如果您有非法的HTML,则不应期望您的代码正常工作。
Text may not be a direct child of a table
. 文本可能不是
table
的直接子项。 You need a tr
and either a td
or a th
. 你需要一个
tr
和td
或th
。 The browser reinterprets your HTML and makes something legal. 浏览器会重新解释您的HTML并使某些内容合法化。 In this case, it puts the text outside the table:
在这种情况下,它将文本放在表格之外:
jjj
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="three body"></table>
This is taken from Chrome's DOM inspector. 这取自Chrome的DOM检查员。 The solution is to put the text legally inside the
table
. 解决方案是将文本合法地放在
table
。
Use this
instead of e.target
. 使用
this
而不是e.target
。
e.target
will give you the clicked element, not the element where the event has been attached to. e.target
将为您提供已单击的元素,而不是已附加事件的元素。 When the element where the event has been attached to has child-elements this and you click on a child-element e.target
will return the child-element. 当附加了事件的元素具有子元素时,单击子元素
e.target
将返回子元素。
alert(this.className);
table
elements cannot have any text content so, your html will actually be rendered as table
元素不能有任何文本内容,因此,您的html实际上将呈现为
<div class="one body">
sd
</div>
<div class="two body">
sddsd
</div>
jjj<table class="three body" border="0" cellpadding="0" cellspacing="0" width="100%"></table>
Which is why your event handler is not firing when you click on jjj
这就是为什么单击
jjj
时没有触发事件处理程序的原因
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.