单击另一列时更改标题的Javascript

时间:2012-01-28 01:46:43

标签: javascript sorting html-table title

我有一个表,在点击另一列中的标题后,我想重置任何其他列以表示排序依据。目前我有:

<html>
<head>
<script>
 function changeSort(obj)
 {  

  var firstName = document.getElementById('fName');
 var lastName = document.getElementById('lName');
 var phoneNumber = document.getElementById('phone');
var birthDate = document.getElementById('birth');


if(obj.id == 'fName')
{
//alert("fName");
 obj.title = (obj.title== 'sort ascending first name') ? 'sort descending first 
 name' : 'sort         ascending first name';   
 }

if(obj.id == 'lName')
{
 //alert("lName");
 obj.title = (obj.title== 'sort ascending last name') ? 'sort descending first name' : 'sort   
ascending last name';   
 }

 if(obj.id == 'phone')
  {
  //alert("phone");
  obj.title = (obj.title== 'sort ascending phone number') ? 'sort descending phone  
  number' : 'sort ascending phone number';   
  }

 if(obj.id == 'birth')
 {
  //alert("birth");
   obj.title = (obj.title== 'sort ascending birth date') ? 'sort descending birth      
   date' : 'sort   
  ascending birth date';   
   }   

   }

  </script>
 </head>
 <body

     <table> 

  <tr>
            <th id="fName" onclick='changeSort(this)' title="sort by First Name" >First Name</th>
    <th id="lName" onclick='changeSort(this)' title="sort by Last Name" >Last   
    Name</th>
    <th id="phone" onclick='changeSort(this)' title="sort by Phone Number" >Phone   
   Number</th>
    <th id="birth" onclick='changeSort(this)'title="sort by Birth Date" >Birth   
    Date</th>
    </tr>

   </table>

  </body>
  </html>

当我对第一列执行排序时,我希望它将标题更改为当前的升序或降序但如果我决定要按姓氏排序,我希望将名字列标题更改回来按名字排序,不是升序或降序。当另一个桌面头被克隆时,如何才能获得已更改的表头的标题以恢复默认值?

2 个答案:

答案 0 :(得分:1)

在你应该添加的函数的末尾:

firstName.title = obj.id == 'fName'? firstName.title : 'sort by first name';
lastName.title = obj.id == 'lName'? lastName.title : 'sort by last name';
phoneNumber.title = obj.id == 'phone'? phoneNumber.title : 'sort by phone number';
birthDate.title = obj.id == 'birth'? birthDate.title : 'sort by birth date';

有更简洁的方法可以做到这一点,但我们必须重构整个代码......

答案 1 :(得分:1)

接受André的观点,即有更简洁的方法,这里的代码经过重构,使其独立于列数,而且更加通用。

function changeSort(th){
    var titleTemplates = {
        asc:  'sort ascending %s',
        desc: 'sort decending %s',
        dflt: 'sort by %s'
    };
    titleTemplates.get = function(key, txt){
        var t = this[key] || this.dflt;
        return t.replace('%s', txt);
    };
    var headerRow = th.parentNode;
    var cells = headerRow.getElementsByTagName('th');
    for(var i=0; i<cells.length; i++){
        var c = cells[i];
        var s = c.getAttribute('sortCode');
        var s_ = (c !== th) ? '' : (!s || s == 'desc') ? 'asc' : 'desc';
        c.setAttribute('sortCode', s_);
        c.title = titleTemplates.get(s_, c.innerHTML);
    }
}

在Opera 11.61中测试

你可以(并且真的应该)通过将点击处理程序附加到javascript而不是HTML中的TH元素来进一步发展。