2015-04-06 60 views
1

我想合併列2的值與我的表中的列3,我的表具有超過20行。jquery將表第二列值合併到下一列值

我正在爲class =「column2」添加第2列的類,爲class =「column3」添加了3。 和我的表類名是genTable。

如何將每個列中的2個值合併到列3..eg中。在第二欄我有'名字'和第三欄我有'姓'作爲測試,然後在這個腳本我想看到'姓氏姓'一起incolumn 3所有的列?

JS:

$(document).ready(function(){ 
    $(".genTable tr").each(function(){ 
      var col2value = $(".column2").text(); 
      var col3value = $(".column3").text(); 
      $(col2value).append(col3value); 
    }) 
}); 

如何給他人所有行每一列的值合併嗎?我們需要使用for循環嗎?

+0

http://jsfiddle.net/arunpjohny/z8k1efk6/1/ – 2015-04-06 07:59:52

回答

0

您可以附加column3內容column2,之後從表中刪除column3

$(".genTable tr .column2").append(function() { 
    return ' ' + $(this).next('.column3').remove().html(); 
}); 

查看下面的演示。

$(".genTable tr .column2").append(function() { 
 
    return ' ' + $(this).next().remove().html(); 
 
});
table {border-collapse: collapse;} 
 
table td, table th {padding: 10px 5px; border: 1px #AAA solid;} 
 
table th {background: #EEE;} 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table class="genTable"> 
 
    <tr> 
 
     <th>ID</th> 
 
     <th class="column2">First name</th> 
 
     <th class="column3">Last name</th> 
 
     <th>Occupation</th> 
 
    </tr> 
 
    <tr> 
 
     <td>1</td> 
 
     <td class="column2">Thomas</td> 
 
     <td class="column3">Mann</td> 
 
     <td>Writer</td> 
 
    </tr> 
 
    <tr> 
 
     <td>2</td> 
 
     <td class="column2">Jon</td> 
 
     <td class="column3">Smith</td> 
 
     <td>Artist</td> 
 
    </tr> 
 
</table>

+0

嗨,感謝您的解決方案。但在哪裏我需要調用「公共類用戶」,以及如何在$(「。genTable tr .column2」)內引用?我想在我準備好的時候打電話給「公共班級用戶」嗎?或單獨的腳本?如何操作只使用dom?而不是定義公共...因爲我在我的jqgrid中也有同樣的... – Krish 2015-04-06 08:19:11

+0

嗯..你在說什麼「公共類用戶」? – dfsq 2015-04-06 08:21:22

+0

在您的代碼中:$(「。genTable tr .column2」)。append(function(){ return''+ $(this).next('。column3')。remove()。html(); } );它如何合併這兩個值? – Krish 2015-04-06 08:24:48

0

1.方案1:使用jQuery 最接近()下()函數。

$(document).ready(function(){ 
     $(".genTable tr td.column2").each(function(){ 
      var col2value = $(this).text();// replace text() with html() to get/set entire html inside selected html element 
      var col3value = $(this).next("td.column3").text(); 
      $(this).text(col2value + " " + col3value); 
     }); 
}); 

See here ...

2.選項2:多一個屬性添加到您的類(說你的類名是用戶)

public class User 
    { 
     public string FirstName {get; set;} 
     public string LastName {get; set;} 
     public string FullName {get {return FirstName + LastName ;}} 
    } 
+0

謝謝您對我是否有空白單元格(col3value)任何想法認爲「無效」作爲文本相應的列2。如何避免這種情況? - – Krish 2015-04-06 10:16:59

+0

克里希,我已經用鏈接更新了我的答案https://jsfiddle.net/ahnr263u/ – RollerCosta 2015-04-06 14:37:12

+0

感謝您的更新。現在我們正在將這些值作爲文本正確的進行協調,相反我們可以將整個html結構移動到下一列,因爲我可能不僅有文本值也可以用於錨元素或一些點擊事件。在那種情況下我們該如何處理? – Krish 2015-04-07 03:05:13

相關問題