2017-05-23 54 views
1

如果用戶點擊img元素警報顯示test-imagetwo-side-text。不過我的需求是隻顯示test-image。我怎樣才能做到這一點?單擊事件嵌套表td元素沒有第一個表td

$("body").on('click', 'td', function(evt) { 
 
    alert($(this).attr('class')); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tbody> 
 
    <tr> 
 
     <td class="Two-side-text"> 
 
     <table> 
 
      <tbody> 
 
      <tr> 
 
       <td class="test-image"> 
 
       <img src="img-placeholder.png"> 
 
       </td> 
 
      </tr> 
 
      </tbody> 
 
     </table> 
 
     <table> 
 
      <tbody> 
 
      <tr> 
 
       <td class="test-paragraph"> 
 
       <p> 
 
        test paragraph 
 
       </p> 
 
       </td> 
 
      </tr> 
 
      </tbody> 
 
     </table> 
 
     </td> 
 
    </tr> 
 
    </tbody> 
 
</table>

回答

2

你需要停止該事件的DOM冒泡到父td元素。要做到這一點,你可以調用stopPropagation()上的事件,就像這樣:

$(document).on('click', 'td', function(evt) { 
 
    evt.stopPropagation(); 
 
    alert($(this).attr('class')); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tbody> 
 
    <tr> 
 
     <td class="Two-side-text"> 
 
     <table> 
 
      <tbody> 
 
      <tr> 
 
       <td class="test-image"> 
 
       <img src="img-placeholder.png"> 
 
       </td> 
 
      </tr> 
 
      </tbody> 
 
     </table> 
 
     <table> 
 
      <tbody> 
 
      <tr> 
 
       <td class="test-paragraph"> 
 
       <p> 
 
        test paragraph 
 
       </p> 
 
       </td> 
 
      </tr> 
 
      </tbody> 
 
     </table> 
 
     </td> 
 
    </tr> 
 
    </tbody>

+0

好吧,我沒有看到你的答案,會刪除我的。 –

+0

謝謝..我會試試這個 –