形式:
<label>First Name:</label><input type="name" class="form-control" id="fname">
<label>Last Name:</label><input type="name" class="form-control" id="lname">
<button class="btn btn-primary" id="add">Add</button>
如果我点击添加按钮,我会在表格中添加名字和姓氏。
表格
<table class="table table-bordered" id="table">
<thead><tr><td>S.N.</td><td>First Name</td><td>Last Name</td><td>Options</td></tr></thead>
<tbody id="tbody"></tbody>
</table>
jQuery的:
$(function(){
var i=0;
$(document).on('click', '#add', function (e)
{
e.preventDefault();
var fname=$('#fname').val();
var lname=$('#lname').val();
if(fname=='' || lname=='')
{
swal('Both fields are required!');
}
else
{
i++;
$('#tbody').append('<tr><td>'+i+'</td><td>'+fname+'</td><td>'+lname+'</td><td><button id="view" class="btn btn-info">Details</button></td></tr>');
$('#showf').append(fname);
$('#showl').append(lname);
}
document.getElementById('fname').value = "";
document.getElementById('lname').value = "";
});
});
现在,如果点击详细信息,我需要显示相应的名字和姓氏。
$(document).on('click', '#view', function (e) {
swal('I am trying. ...');
});
答案 0 :(得分:2)
你可以这样做。您正在复制标识#view
使用类view
。
$(document).on('click', '.view', function(e) {
var tr = $(this).closest('tr');
var firstName = tr.find('td').eq(1).text();
var lastName = tr.find('td').eq(2).text();
alert(firstName + ' ' + lastName);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-bordered" id="table">
<thead><tr><td>S.N.</td><td>First Name</td><td>Last Name</td><td>Options</td></tr></thead>
<tbody id="tbody">
<tr>
<td>1</td>
<td>fname</td>
<td>lname</td>
<td><button class="view btn btn-info">Details</button></td>
</tr>
<tr>
<td>2</td>
<td>fname 2</td>
<td>lname 2</td>
<td><button class="view btn btn-info">Details</button></td>
</tr>
</tbody>
</table>
&#13;