2012-08-14 50 views
1

一個表中的每一TD我哈瓦2個表添加title屬性基於值

<table class="first"> 
    <thead> 
      <th> header1</td> 
      <th> header2 </th> 
    </thead> 
    <tbody> 
      <tr> 
       <td>hi</td> 
       <td>hello</td> 
      </tr> 
    </tbody> 
</table> 


<table class="second"> 
    <thead> 
      <th> header1</td> 
      <th> header2 </th> 
    </thead> 
    <tbody> 
      <tr> 
       <td>hi</td> 
       <td>hello</td> 
      </tr> 
      <tr> 
       <td>hi</td> 
       <td>hello</td> 
      </tr> 
    </tbody> 
</table> 

現在我的jQuery部分:

var trainingInstanceIds = ${trainingInstance.id}; 
    alert(trainingInstanceIds) // which prints say 1,9, 

現在我想第二個表的每一個TD有在trainingInstanceIds給出的標題作爲值

基本上,我想是這樣的

<table class="second"> 
    <thead> 
      <th> header1</td> 
      <th> header2 </th> 
    </thead> 
    <tbody> 
      <tr> 
       <td title="1">hi</td> 
       <td title="9">hello</td> 
      </tr> 
      <tr> 
       <td title="1">hi</td> 
       <td title="9">hello</td> 
      </tr> 
    </tbody> 
</table> 

trainingInstanceIds的值和td的數量會發生變化。

這裏我想給已經創建的表添加標題

怎麼辦?

$.each(trainingInstanceIds, function(index, value) { 

    }); 
+1

如果它的動態創建的,你可以在首先生成表的代碼做呢? – 2012-08-14 10:18:07

+0

我想爲已經創建的表添加標題 – monda 2012-08-14 10:19:44

回答

1

試試這個,如果trainingInstanceIds是以數組的形式出現的話。

$.each(trainingInstanceIds, function(index, value) { 
    $('.second td:eq('+ index+')').prop('title', value); 
}); 

或使用,如果trainingInstanceIds來作爲字符串

$.each(trainingInstanceIds.split(','), function(index, value) { 
    $('.second td:eq('+ index+')').prop('title', value); 
}); 

,並檢查該DEMO

+0

未捕獲TypeError:對象1,9沒有方法「拆分」 – monda 2012-08-14 10:27:02

+0

trainingInstanceIds作爲字符串或對象傳入 – 2012-08-14 10:28:23

+0

Object ............. ..... – monda 2012-08-14 10:31:25

1

這可能會產生更好的性能來遍歷td S的代替IDS:

var trainingInstanceArray = trainingInstanceIds.split(','); 

$('.second td').each(function(index, element) { 
    var $el = $(this); 
    $el.attr('title', trainingInstanceArray[$el.index()]); 
}); 

編輯:我錯過了你想要每一行的每一個標題。上面更新。

1
// I suppose that trainingInstanceIds is a table 
$.each($("table.second tbody tr"), function(){ 
    var tds = $(this).find("td"); 
    $.each(trainingInstanceIds, function(index, value) { 
     $(tds[index]).attr("title", value); 
    }); 
}); 

我覺得這樣。但你認爲屬性標題不符合W3C標準。

+0

它不會添加標題動態添加tds – monda 2012-08-14 10:36:12

+0

但適用於常規tds,不適用於動態添加tds – monda 2012-08-14 10:37:10

+2

如果您替換$ .each(tr,.. 。with $ .each('table.second tbody tr',..它應該在動態添加。 – fredrik 2012-08-14 10:41:09

3

你可以只通過一個函數來jQuery的attr - 方法:

var trainingInstanceArray = [1, 9]; 
// OR use if it's a string: 
var trainingInstanceArray = trainingInstanceIds.split(',') 
$('.second td').attr('title', function (index, attr) { 
    return trainingInstanceArray[$(this).index()]; 
});​ 

Example at JSFiddle

+0

更好,最簡單的解決方案 – 2012-08-14 12:58:27