2015-09-21 28 views
0

我有一個JavaScript,它使HTML中的表格可排序。不過,我想對使用javascript單擊的列的標題進行樣式設置。如何更改表格中點擊的樣式

我怎樣才能得到表的?我知道我需要更改的標題欄。

這是我的JavaScript現在返回給我的東西。

的javascript

console.log(table.tHead); 

輸出到控制檯:

<thead> 
     <tr> 
      <th>Name</th> 
      <th>Times Placed</th> 
      <th>UMF (KB)</th> 
      <th>UAC</th> 
      <th>Texture Memory (MB)</th> 
      <th>Texture Count</th> 
      <th>Mesh Memory (KB)</th> 
      <th>Mesh Count</th> 
      <th>Path</th> 
     </tr> 
</thead> 
+0

你怎麼想呢? –

+0

你可以只讓文本藍色 – JokerMartini

+0

檢查我的答案。 –

回答

3

這將一個selected類添加到點擊th元件,將它從一個previously-除去selected類點擊th

document.querySelector('thead').addEventListener('click', function(e) { 
 
    var current; 
 
    if (e.target.tagName === 'TH') { 
 
    current = document.querySelector('th.selected'); 
 
    if (current) { 
 
     current.classList.remove('selected'); 
 
    } 
 
    e.target.classList.add('selected'); 
 
    } 
 
});
th { 
 
    border: 1px solid #bbb; 
 
    padding: 0.5em; 
 
} 
 
.selected { 
 
    background: #def; 
 
}
<table> 
 
    <thead> 
 
    <tr> 
 
     <th>Name</th> 
 
     <th>Times Placed</th> 
 
     <th>UMF (KB)</th> 
 
     <th>UAC</th> 
 
     <th>Texture Memory (MB)</th> 
 
     <th>Texture Count</th> 
 
     <th>Mesh Memory (KB)</th> 
 
     <th>Mesh Count</th> 
 
     <th>Path</th> 
 
    </tr> 
 
    </thead> 
 
</table>

應該與您現有的代碼工作,假設您的網頁上只有一個表。

+1

的副本很高興看到一些** Javascript ** – sabithpocker

0

function makeMeBlue(element) { 
 
    element.style.color = 'blue'; 
 
}
<table id="table"> 
 
    <thead> 
 
    <tr> 
 
     <th onclick="makeMeBlue(this)">Name</th> 
 
     <th onclick="makeMeBlue(this)">Times Placed</th> 
 
     <th onclick="makeMeBlue(this)">UMF (KB)</th> 
 
     <th onclick="makeMeBlue(this)">UAC</th> 
 
     <th onclick="makeMeBlue(this)">Texture Memory (MB)</th> 
 
     <th onclick="makeMeBlue(this)">Texture Count</th> 
 
     <th onclick="makeMeBlue(this)">Mesh Memory (KB)</th> 
 
     <th onclick="makeMeBlue(this)">Mesh Count</th> 
 
     <th onclick="makeMeBlue(this)">Path</th> 
 
    </tr> 
 
    </thead> 
 
</table>