簡體   English   中英

e.target()不適用於表元素

[英]e.target() not working for table element

event.target函數適用於div而不適用於table元素。

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:

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


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

演示: http//jsfiddle.net/kavinhuh/z4rkW/31/

因為實際e.target是TD,而不是表
雖然您有不正確的表HTML元素結構。 表應具有trtd元素。

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

//是首先觸發事件的元素( TD

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

//是委托給事件的元素,在本例中為.body

這是因為您的HTML是非法的。 如果您有非法的HTML,則不應期望您的代碼正常工作。

文本可能不是table的直接子項。 你需要一個trtdth 瀏覽器會重新解釋您的HTML並使某些內容合法化。 在這種情況下,它將文本放在表格之外:

    jjj
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="three body"></table>

這取自Chrome的DOM檢查員。 解決方案是將文本合法地放在table

使用this而不是e.target

e.target將為您提供已單擊的元素,而不是已附加事件的元素。 當附加了事件的元素具有子元素時,單擊子元素e.target將返回子元素。

alert(this.className);

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>

這就是為什么單擊jjj時沒有觸發事件處理程序的原因

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM