2016-07-15 151 views
0

我有這樣的結構搶表格單元格中的文本

<tr> 
    <th>some text0</th> 
    <th>some text1</th> 
    <th>some text2</th> 
    <td class="edit"><button>Edit</button></td> 
</tr> 

當單擊編輯按鈕,我想採取「一些文字0,1和2」,並將該表格內。

我試圖使用JQuery Traversing中的方法,但沒有成功。

一個例子

$(document.body).on('click', '.edit' ,function(){ 
    var takeit = $(this).parent('tr th:eq(0)').html(); 
    $('.a_input_for_my_form').val(takeit);; 
}); 

另一個

$(document.body).on('click', '.edit' ,function(){ 
    var father = $(this).parent('tr th:eq(0)'); 
    var child = $(father).child('th').html(); 
    $('.a_input_for_my_form').val(child); 
}); 

回答

1

只是我猜你的預期?如果不是讓我知道

$(document.body).on('click', '.edit' ,function(){ 
    var takeit = $(this).closest('tr').find('th').eq(0).html(); 
    $('.a_input_for_my_form').val(takeit); 
}); 

DEMO

+1

謝謝!它的工作! – Ini

1

我創建了兩個演示,並連接每一個演示,以不同的按鈕

其中一個演示可以幫助

$('#btn1').click(function(){ 
 
    //Grabs all text in all `th` 
 
    var txt = $('table tr th').text(); 
 
    $('.myInput').val(txt); 
 
}); 
 

 
$('#btn2').click(function(){ 
 
    //Iterates through each `th`, sticks text into array, converts to string 
 
    var txt = []; 
 
    $('table tr th').each(function(){ 
 
    txt.push($(this).text()); 
 
    }); 
 
    $('.myInput').val(txt.join(", ")); 
 
});
*{position:relative;} 
 
form{margin-top:15px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<table> 
 
<tr> 
 
    <th>some text0</th> 
 
    <th>some text1</th> 
 
    <th>some text2</th> 
 
</tr> 
 
<tr> 
 
    <td class="edit"><button id="btn1">Edit1</button></td> 
 
    <td class="edit"><button id="btn2">Edit2</button></td> 
 
</tr> 
 

 
</table> 
 
<form> 
 
    <input class="myInput" type="text" /> 
 
</form>

+0

謝謝!這是有幫助的 – Ini

相關問題