简体   繁体   中英

e.target() not working for table element

The event.target function works well for div and not for table element.

html code:

<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:

$(".body").click(function(e){


    alert("xxxxxxxxx"+e.target.className);
});

DEMO: http://jsfiddle.net/kavinhuh/z4rkW/31/

Cause the actual e.target is a TD, not a table
Though you have an incorrect Table HTML Element structure. Tables are expected to have tr and td elements.

alert("Class: "+ event.target.className );

// is the Element that first fired the event ( TD )

alert("Class: "+ this.className ); 

// is the element that was delegated to the event, in this case .body

This is because your HTML is illegal. If you have illegal HTML, you should not expect your code to work properly.

Text may not be a direct child of a table . You need a tr and either a td or a th . The browser reinterprets your HTML and makes something legal. 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. The solution is to put the text legally inside the table .

Use this instead of e.target .

e.target will give you the clicked element, not the element where the event has been attached to. 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.

alert(this.className);

table elements cannot have any text content so, your html will actually be rendered as

  <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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM