2016-07-15 86 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

相关问题