I think it's a bad idea to declare a listener inside a function that you'll call several times, because you'll have many listeners.
Also, if your table has headers, you should restrict the listener to td
that are within tbody
.
Now, suppose that anyway you want documento
to have a value before the click. One way would be to initialize your value as if someone had punctured the first row:
(copying the response from Pablo Lozano ) click on the button before clicking on the table:
var documento = $('#documentos-table tbody').find('td').first().text();
function getDocumento() {
console.log('documento actual es ', documento);
return documento;
}
$('#documentos-table tbody tr').click(function(e) {
documento = $(this).find('td').first().text();
getDocumento();
});
$('#verdocumento').on('click', getDocumento);
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="verdocumento">Ver documento actual</button>
<table id="documentos-table">
<thead>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</tbody>
</table>