2016-06-08 42 views
0

我想添加一個類打開元素類菜單當用戶點擊THEAD TR日,如下表我的如何添加一個類到一個元素時,在jQuery中點擊了表?

這是我的表

<div><ul> 
<li class="menus"> 
    <a></a> 
    <ul><li> 
    <table id="tableid "> 
     <thead> 
      <tr><th></th><th></th><th></th></tr> 
     </thead> 
     <tbody> 
      <tr id="1"> 
       <td></td> 
       <td id="type1">types1</td> 
       <td></td> 
       <td id="types2">types2</td> 
       <td></td> 
      </tr> 
      <tr id="2"> 
       <td></td> 
       <td id="type1">types3</td> 
       <td></td> 
       <td id="types2">types4</td> 
       <td></td> 
      </tr> 
      </tbody> 
     </table> 
    </li> 
    </ul> 
</li></ul></div> 

JS

$(document).on('click','#tableid thead tr th', function(){ 
    var parents = $(this).prevAll().find('li') 
    console.log(parents) 

}); 
+2

HTML結構是無效的。 'div'不能成爲'ul'和'tbody'的一部分....嗯,'

'哪裏? – Tushar

+0

使用手風琴而不是...如果我明白你想要做什麼 –

+0

你的表創建語法不正確。請更新您的代碼 – GSB

回答

2

使用.parents.addClass

$(document).on('click','#tableid thead tr th', function(){ 
    var parents = $(this).parents('li.menus').addClass('open') 
    console.log(parents) 
}); 
+0

我已經使用此var父母= $(this).offsetParent()。offsetParent()。offsetParent();雖然它的工作,但它應該更好,或者我們應該使用循環來找到它或什麼 –

+0

有沒有用它來使用循環,你的代碼可能工作完美,但由於其冗長而沒有必要,我們應該選擇'.parents' –

相關問題